Function Composition and Pipes

In Elm the operator for function composition is >>:

f >> g = f(g) = g << f

There is also the operator << that reverses the order of operation.

In addition there is also the |> pipe operator that allows us to pass the output of one expression as the last argument of the next function. (Exercise: verify that it is passed as the last argument.)

Here are some examples of using the function composition and pipe operators.

import Graphics.Element exposing (..)

isEven : Int -> Bool
isEven n =
   n % 2 == 0

isOdd : Int -> Bool
isOdd x = not(isEven x)

isOdd1 : Int -> Bool
isOdd1 = not << isEven

isOdd2 : Int -> Bool
isOdd2 x = x |> isEven |> not

isOdd3 : Int -> Bool
isOdd3 x =   not <| isEven <| x

main = flow down [
              print "IsEven (3) : " (isEven 3)
             ,print "IsOdd (3) : " (isOdd 3)
             ,print "IsOdd1 (3) : " (isOdd1 3)
             ,print "IsOdd2 (3) : " (isOdd2 3)
             ,print "IsOdd3 (3) : " (isOdd3 3)
            ]

--a helper function to make display easier
print message value = show (message ++ (toString value))

results matching ""

    No results matching ""