16

I wrote a function in Haskell

toInt :: Float -> Int
toInt x = round $fromIntegral x

It is supposed to take in an Float and return the equivalent Int. I come from a C programming background, and in C, we could just cast it as an int.

However, in this case, I get the following compile error

No instance for (Integral Float)
arising from a use of `fromIntegral'
In the second argument of `($)', namely `fromIntegral x'
In the expression: round $ fromIntegral x
In an equation for `toInt': toInt x = round $ fromIntegral x

Any idea on how to fix this?

2
  • Maybe you can try this round 3.2 :: Int. Commented Mar 23, 2017 at 11:58
  • 3
    If you need to find a function that you know the type like Float -> Int then your can search for functions of that type either on Hayoo or Hoogle Commented Mar 23, 2017 at 13:19

1 Answer 1

22

Your type annotation specifies that x should be a Float, which means it can't be a parameter to fromIntegral since that function takes an Integral.

You could instead just pass x to round:

toInt :: Float -> Int
toInt x = round x

which in turn can be slimmed down to:

toInt :: Float -> Int
toInt = round

which implies that you may be better off just using round to begin with, unless you have some specialized way of rounding.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked, thanks. I feel so silly after someone tells me a solution in Haskell haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.