When are type signatures necessary in Haskell?

前端 未结 3 519
清酒与你
清酒与你 2020-12-03 13:32

Many introductory texts will tell you that in Haskell type signatures are \"almost always\" optional. Can anybody quantify the \"almost\" part?

As far as I can tell,

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 14:19

    Polymorphic recursion needs type annotations, in general.

    f :: (a -> a) -> (a -> b) -> Int -> a -> b
    f f1 g n x = 
        if n == (0 :: Int)
        then g x
        else f f1 (\z h -> g (h z)) (n-1) x f1
    

    (Credit: Patrick Cousot)

    Note how the recursive call looks badly typed (!): it calls itself with five arguments, despite f having only four! Then remember that b can be instantiated with c -> d, which causes an extra argument to appear.

    The above contrived example computes

    f f1 g n x = g (f1 (f1 (f1 ... (f1 x))))
    

    where f1 is applied n times. Of course, there is a much simpler way to write an equivalent program.

提交回复
热议问题