Search code examples
haskellparametershigher-order-functions

High order Function not taking right parameter


I have an exercise to make a higher order function in haskell which takes another func I created.

multiplyFive :: [Int] -> [Int]
multiplyFive [] = []
multiplyFive (x:xs) = (x * 5) : multiplyFive xs

then I create this funct to add all the numbers that is in the list given

addAll :: ([Int] -> [Int]) -> [Int] -> Int
addAll fn [] = 0
addAll fn (x:xs) = x + addAll fn xs

I am trying to do this

main :: IO()
main = do 
    print(addAll multiplyFive [1..4])

The output should be 50 but it gives me an output of 10


Solution

  • You only pass fn to recursive calls, you don't use fn to apply this on elements. The addAll thus should be:

    addAll :: ([Int] -> [Int]) -> [Int] -> Int
    addAll fn xs = go (fn xs)
      where go [] = 0
            go (x : xs) = x + go xs

    the function can however be simplified to:

    addAll :: (Foldable f, Num b) => (a -> f b) -> a -> b
    addAll = (sum .)
    

    and multiplyFive is just:

    multiplyFive :: Num a => [a] -> [a]
    multiplyFive = map (5 *)