Home > Net >  Mapping an element to a list of functions in Haskell
Mapping an element to a list of functions in Haskell

Time:05-26

The Prelude function map in Haskell applies a function to a list of inputs:

map :: (a -> b) -> [a] -> [b]

If we would like to apply an element to a list of functions, we could do this with recursion:

functionMap :: a -> [a -> b] -> [b]
functionMap element functions = case functions of
  []   -> []
  x:xs -> x element : functionMap element xs

How could we simplify the above recursion with higher order functions, such as foldl, foldr or map, if it is possible?

CodePudding user response:

You can map over the functions and apply each to element:

functionMap :: a -> [a -> b] -> [b]
functionMap element functions = map (\f -> f element) functions

This can be shortened using the $ operator to:

functionMap :: a -> [a -> b] -> [b]
functionMap element functions = map ($ element) functions

or just:

functionMap :: a -> [a -> b] -> [b]
functionMap element = map ($ element)

(also: functionMap = map . flip id)

  • Related