Using a filtered list in a new function in haskell

后端 未结 3 749
再見小時候
再見小時候 2021-01-19 05:56

So i\'m not too sure how to phrase this properly, but say I wanted to get the sum of all odd numbers in a list, do I have two functions (sumList and getOddNumbers) and combi

3条回答
  •  余生分开走
    2021-01-19 06:38

    Passing output as input to (another) function

    Well what you basically want to do is use the output of the getOddNumbers as input for the sumList function, so we can define a sumOddList function as:

    sumOddList :: [Integer] -> Integer
    sumOddList l = sumList (getOddNumbers l)
    

    Here l is the list we want to process, and the result is thus a function application on the result of getOddNumbers l (with sumList the function).

    Chaining functions: the (.) function

    The above pattern is quite common: frequently we want to pass data first through a function g, and the result through a function f. Haskell has the (.) :: (b -> c) -> (a -> b) -> a -> c function to "chain" functions. We can thus chain sumList and getOddNumbers together like:

    sumOddList :: [Integer] -> Integer
    sumOddList = (.) sumList getOddNumbers
    

    Notice that we no longer use an l parameter here. sumOddList is here defined as a "pipeline" where data is first passed to the getOddNumbers, and then is "post-processed" by the sumList function.

    The (.) function can also be used as an infix operator:

    sumOddList :: [Integer] -> Integer
    sumOddList = sumList . getOddNumbers
    

提交回复
热议问题