Haskell: how to infer the type of an expression manually

后端 未结 5 891
难免孤独
难免孤独 2020-12-05 15:58

Given ist the Haskell function:

head . filter fst

The question is now how to find the type \"manually\" by hand. If I let Haskell tell me t

5条回答
  •  日久生厌
    2020-12-05 16:28

    filter :: (a -> Bool) -> [a] -> [a] takes a function (a -> Bool), a list of the same type a, and also returns a list of that type a.

    In your defintion you use filter fst with fst :: (a,b) -> a so the type

    filter (fst :: (Bool,b) -> Bool) :: [(Bool,b)] -> [(Bool,b)]
    

    is inferred. Next, you compose your result [(Bool,b)] with head :: [a] -> a.

    (.) :: (b -> c) -> (a -> b) -> a -> c is the composition of two functions, func2 :: (b -> c) and func1 :: (a -> b). In your case, you have

    func2 = head       ::               [ a      ]  -> a
    

    and

    func1 = filter fst :: [(Bool,b)] -> [(Bool,b)]
    

    so head here takes [(Bool,b)] as argument and returns (Bool,b) per definition. In the end you have:

    head . filter fst :: [(Bool,b)] -> (Bool,b)
    

提交回复
热议问题