Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: "Cast" / force type?

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.

like image 831
user905686 Avatar asked Dec 19 '11 18:12

user905686


2 Answers

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.

like image 160
Prateek Avatar answered Sep 19 '22 22:09

Prateek


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

like image 34
mipadi Avatar answered Sep 17 '22 22:09

mipadi