Haskell: "Cast" / force type?

How can I say that Haskell interprets something as a special type? For example, I have a list and I want to divide its length by 2. Therefore, I write

(length mylist) / 2 

and get this error

No instance for (Fractional Int) arising from the use of `/ '

How I want integer division, I would like to make length mylist , 2 and result Int .

+6
source share
2 answers

There are two different problems here.

  • Integer division: use the div function: div (length mylist) 2 or (length mylist) `div` 2

  • Casting

    . You can tell Haskell that a particular expression is of a specific type by writing expression :: type instead of just expression . However, this does not do any “casting” or “conversion” of values. Some useful functions for converting between different numeric and string types: fromIntegral , show , read , realToFrac , fromRational , toRational , toInteger and others. You can watch them on Hoogle .

+11
source

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

+5
source

Source: https://habr.com/ru/post/904107/


All Articles