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 div function : div (length mylist) 2 or (length mylist) `div` 2
Casting. One can tell Haskell that a particular expression has a particular type by writing expression :: type instead of just expression. However, this doesn't do any "casting" or "conversion" of values. Some useful functions for converting between various numeric and string types are fromIntegral, show, read, realToFrac, fromRational, toRational, toInteger, and others. You can look these up on Hoogle.
Try div (length my list) 2. / does fractional division; div does integer division.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With