Haskell, multiplying Int and Float within a function

后端 未结 4 2073
故里飘歌
故里飘歌 2021-01-01 10:41

Why is it that in ghci I can enter:

5.0 * (3 - 1)
> 10.0

But if I try and create a function in a .hs file and load it in:



        
4条回答
  •  难免孤独
    2021-01-01 11:44

    You need to use fromIntegral on the integers before multiplying by the floats.

    http://www.haskell.org/haskellwiki/Converting_numbers

    In GHCI, the numbers aren't assumed to be floats or ints until you use them. (e.g: at run time). That works out better for REPL-style development.

    In the compiler proper, there isn't any automatic coercion. It it sees the multiplication assumes that the two values must belong to a type-class that supports multiplication. e.g: multiplying ints , or multiplying floats. As you didn't use any other explicitly typed functions, it assumed ints. That assumption then differs with your (optional) type signature.

提交回复
热议问题