Haskell function composition

后端 未结 6 1485
梦如初夏
梦如初夏 2021-02-01 14:42

I am reading this tutorial on Haskell. They define function composition as the following:

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


        
6条回答
  •  一生所求
    2021-02-01 15:24

    Function composition is a way to "compose" two functions together into a single function. Here's an example:

    Say you have these functions:

    even :: Int -> Bool
    not :: Bool -> Bool
    

    and you want to define your own myOdd :: Int -> Bool function using the two above.

    The obvious way to do this is the following:

    myOdd :: Int -> Bool
    myOdd x = not (even x)
    

    But this can be done more succinctly using function composition:

    myOdd :: Int -> Bool
    myOdd = not . even
    

    The myOdd functions behave exactly the same, but the second one is created by "glue-ing" two functions together.

    A scenario where this is especially useful is to remove the need for an explicit lambda. E.g:

    map (\x -> not (even x)) [1..9]
    

    can be rewritten to:

    map (not . even) [1..9]
    

    A bit shorter, less room for errors.

提交回复
热议问题