开发者

Haskell - how can I check if number is Double/Float?

I would like to do smth like:

x `mod` 1.0 == 0 // => int

but it seems mod works only for int... help! EDIT: I am t开发者_如何学Crying to check if given number is triangle, http://en.wikipedia.org/wiki/Triangle_number so my idea was to check if n1 is Int...

(n*(n+1))/2 = s => n1 = (-1 +sqrt(1 + 8s))/2


To determine whether a certain Float or Double is indistinguishable from an Integer in Haskell, use floor and ceiling together. Something like:

if floor n == ceiling n
  then "It was some integer."
  else "It's between integers."

There might also be some fancy stuff you can do with the float's representation in binary, exposed by the RealFloat typeclass:

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t%3ARealFloat


A better way to check if a number is triangular is to generate a list of triangular numbers and then see if your candidate is in it. Since this is a learning problem I'm going to give hints rather than the answer.

Use a list comprehension to generate the triangular numbers.

Since they will be in order you can find out if you have gone past them.

An alternative approach if you are working with big numbers would be to use a binary search to narrow down the number of rows that might give rise to your candidate.


Total edit:

Okay, I'm still not sure what you're trying to accomplish here.

  • First, anything modulo 1 is going to be zero, because the modulo function only makes sense on integers. If you want to take the modulo of a fractional type you can convert to an integer first. Edit: Although for what it's worth, Data.Fixed does have a mod' function for non-integral values.
  • I also don't know what you mean by "check if n1 is Int". Either it is or it isn't; you don't need to check at run time. Edit: Okay, I see now that you're just checking to see if a value has a fractional component. Paul Johnson correctly points out above that it's wise to be careful doing such things with floating point values.
  • If you want to mix mod and sqrt operations in the same calculation, you'll have to manually convert between appropriate types. fromIntegral will convert any integer type into any number type, floor, ceiling, and round will convert fractional types to integral types.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜