I’m trying to make a simple function to return a centered string of text in Haskell, but I’m having trouble just finding how much padding to insert either side. I have this:
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 (basically) convert from an Double (I think) to an Int?
The problem is not that you can’t convert a Double to an Int —
roundaccomplishes that just fine — it’s that you’re trying to do division on an Int (padLength - length string). The error message is just telling you that Int is not an instance ofFractional, the typeclass for numbers that can be divided.In general, you could use
fromIntegral (padLength - length string)to turn it into a Double, but in this case, you can simply use integer division directly:a `div` bis just a nicer way of writingdiv a b; you can use any function as a binary operator like this.