How do I say Haskell to interpret something as a special type?
For example, I have a list and want to divide its length by 2.
So I write
(length mylist) / 2
and get this error
No instance for (Fractional Int)
arising from a use of `/’
As I want a whole-number division, I’d like to make length mylist, 2 and the result Int.
There are two different issues here.
Integer division: Use the
divfunction :div (length mylist) 2or(length mylist) `div` 2Casting. One can tell Haskell that a particular expression has a particular type by writing
expression :: typeinstead of justexpression. However, this doesn’t do any “casting” or “conversion” of values. Some useful functions for converting between various numeric and string types arefromIntegral,show,read,realToFrac,fromRational,toRational,toInteger, and others. You can look these up on Hoogle.