John
John

Reputation: 135

Haskell List Comprehension, delete integers from List of numbers

i want to implement a function in list comprehension. It should deletes the integers in a list of numbers.

And i have a question about it.

delete xs = [ys|ys<-xs, ys /=fromInteger (round ys) ]

xxx.hs> delete [1,2,3.0,4.5,6.7]
        [4.5,6.7]

is that means 3.0 is counted as integer instead of float?

And another question:

delete xs = [ys|ys<-xs, ys ==fromInteger (round ys) ]

this time i want it to return integers from a list of numbers.

xxx.hs> delete [1,2,3.0,4.5,6.7]
       [1.0,2.0,3.0]

since i did not give the number 1 and 2 in decimal form, why it returns the numbers in decimal?

Thanks for helping me.

Upvotes: 2

Views: 137

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

I want to implement a function in list comprehension. It should deletes the integers in a list of numbers.

In a list all elements have the same type. So in a list [1.2, 3, 4.5], the 3 is also a value of a type that is a member of the Floating typeclass.

Since i did not give the number 1 and 2 in decimal form, why it returns the numbers in decimal?

Because all the elements are of the same type. GHC will default to Double by the type defaulting rules.

Your filter does not specify that elements should be of an Integral type. This would also be non-sensical since types are resolved at compile time, not at runtime. It simply checks that ys is the same if you fromInteger (round ys). Since round 3.0 == 3, and fromInteger 3 == 3.0 in this case, it thus filters out elements with a fractional part. 1.0 and 2.0 have no fractional part.

The filtering is however not safe, for larger numbers, the mantisse can not represent every integer exactly, and thus this means that some values will be filtered retained when these are not integeral numbers. For more information, see is floating point math broken.

Upvotes: 2

Related Questions