6
votes

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.

2
JFI there is genericLength function in Data.List. In your case it will not return whole-number answer, but it's generally useful as it lets you avoid some awkward fromIntegral calls.Matvey Aksenov
Needs more fromIntegral. Seriously, though, fromIntegral is the magical way to "cast" an Int to anything that instantiates the Num typeclass.Dan Burton

2 Answers

11
votes

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.

5
votes

Try div (length my list) 2. / does fractional division; div does integer division.