Search code examples
haskellfunctional-programming

Haskell - Apply list of functions to a variable


I have been trying to implement a function that applies a list of functions given as a parameter to a given variable. I have been running into various type errors with infinite types and type mismatches. Below is draft using recursion I believe is close to working, but keep running in to type mismatches. I am hard stuck in this swamp of issues and have no clue how to progress.

applyList :: [a -> b] -> a -> [b]
applyList [] variable = variable
applyList (f:fs) variable = applyList fs $(\f variable -> f variable)

Here is my another draft solution using foldl, no success there either.

applyList :: [a -> a] -> a -> a
applyList fs variable = foldl (\variable f -> f variable) variable fs

Example usage:

   applyList [] "foo" ==> "foo"
   applyList [] 1     ==> 1
   applyList [(++"bar")] "foo" ==> "foobar"
   applyList [reverse, tail, (++"bar")] "foo" ==> "raboo"
   applyList [(3*), (2^), (+1)] 0 ==> 6
   applyList [(+1), (2^), (3*)] 0 ==> 2

Solution

  • Remember that the first element of the list should be the outermost function, which means you don't need to do anything backwards or use foldl. Written explicitly, it'd be like this:

    applyList [] variable = variable
    applyList (f:fs) variable = f (applyList fs variable)
    

    And with foldr:

    applyList = foldr (.) id
    

    Or even better:

    applyList fs variable = foldr ($) variable fs