Haskell, multiplying Int and Float within a function

后端 未结 4 2015
故里飘歌
故里飘歌 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:19

    Your test function was more general, before you add a signature:

    > let test a b c = a * (b - c)
    > :t test
      test :: Num a => a -> a -> a -> a
    

    You could restrict it, but all types must be the same:

    test :: Fractional a => a -> a -> a -> a   -- some real types
    test :: Integral   a => a -> a -> a -> a   -- all integer types
    test :: Float -> Float -> Float -> Float  
    test :: Int   -> Int   -> Int   -> Int   
    
    test :: Int   -> Float -> Float -> Float  --wrong
    

    By the way, 2 isn't Int and 0.2 isn't Float, let ask gchi:

    > :t 2
     2 :: Num a => a
    > :t 0.2
     0.2 :: Fractional a => a
    

提交回复
热议问题