Haskell function composition operator of type (c→d) → (a→b→c) → (a→b→d)

后端 未结 6 680
耶瑟儿~
耶瑟儿~ 2020-11-28 04:21

Ordinary function composition is of the type

(.) :: (b -> c) -> (a -> b) -> a -> c

I figure this should generalize to types

6条回答
  •  半阙折子戏
    2020-11-28 04:26

    As Max pointed out in a comment:

    diffsq = ((^ 2) .) . (-)
    

    You can think of f . g as applying one argument to g, then passing the result to f. (f .) . g applies two arguments to g, then passes the result to f. ((f .) .) . g applies three arguments to g, and so on.

    \f g -> (f .) . g :: (c -> d) -> (a -> b -> c) -> a -> b -> d
    

    If we left-section the composition operator with some function f :: c -> d (partial application with f on the left), we get:

    (f .) :: (b -> c) -> b -> d
    

    So we have this new function which expects a function from b -> c, but our g is a -> b -> c, or equivalently, a -> (b -> c). We need to apply an a before we can get what we need. Well, let's iterate once more:

    ((f .) .) :: (a -> b -> c) -> a -> b -> d
    

提交回复
热议问题