Home > Blockchain >  How to define a function that returns a list or a single element in Haskell?
How to define a function that returns a list or a single element in Haskell?

Time:09-01

I'm completely stuck trying to implement this function below in a simple tutorial exercise. It should apply the second parameter to the last parameter, and then apply the first parameter to the whole thing:

multiApp sum     [(1 ), (^3), ( 2)]      1       ==>  6
multiApp reverse [tail, take 2, reverse] "foo"   ==> ["oof","fo","oo"]

Since the function can return a single element or list, I don't know how to define it, something like this as a start won't even compile:

multiApp :: (β->β) -> [(β->β)] -> β    -> β
multiApp f fs x = f $ map (\i -> i x) fs

CodePudding user response:

You work with an unnecessary restriction on f: you here say f has type β -> β, but why do the input and output types of f need to be of the same type?

You can generalize to:

multiApp :: ([α] -> β) -> [α -> α] -> α -> β
multiApp f fs x = f $ map ($ x) fs

You thus apply each function in the list to the value, and then you call f on the list of these items. For sum this will thus sum up the elements, whereas for reverse, it will reverse the list.

We can in fact further generalize this to:

multiApp :: ([β] -> γ) -> [α -> β] -> α -> γ
multiApp f fs x = f $ map ($ x) fs
  • Related