Converting between types in Haskell

I am trying to make a simple function to return a centered line of text in Haskell, but I am having trouble finding how many indents to insert in either direction. I have it:

center padLength string = round ((padLength - (length string)) / 2)

Which gives the following error:

No instance for (Fractional Int)
  arising from a use of '/'
Possible fix: add an instance declaration for (Fractional Int)
In the first argument of 'round', namely
  '((padLength - (length string)) / 2)'
In the expression: round ((padLength - (length string)) / 2)
In an equation for `center':
    center padLength string = round ((padLength - (length string)) / 2)

How can I (mostly) convert from Double (I think) to Int?

+5
source share
2 answers

The problem is not that you cannot convert Double to Int - roundthis is just fine - this is what you are trying to split into Int ( padLength - length string). The error message simply tells you that Int is not an instance Fractional, typeclass for numbers that can be split.

, fromIntegral (padLength - length string), Double, :

center padLength string = padLength - (length string) `div` 2

a `div` b - div a b; , .

+9

/ , .

Double ( fromIntegral), div.

+1

All Articles