Reputation: 17
Is it possible to code a simple map function which allows to have multiple functions on one argument? for example mapmultiple [square, pred] 4 --> [16, 3]
map1 :: (a -> b) -> [a] -> [b]
map1 f [] = []
map1 f (x:xs) = foldr (\y ys -> (f y):ys) [] xs
map1 allows it with one function but how will it work out with two or three functions?
Upvotes: 1
Views: 3063
Reputation: 70367
This is just map
with the arguments flipped.
map :: (a -> b) -> [a] -> [b]
mapmultiple :: [a -> b] -> a -> [b]
The "function" of map
is going to be a higher-order function applying an argument.
mapmultiple fs x = map ($ x) fs
If you're not comfortable with the $
section, this is equivalent[1] to
mapmultiple fs x = map (\f -> f x) fs
[1] For a time, there was a GHC bug where sections would compile incorrectly to similar (but not quite equivalent) code. I'm uncertain as to whether it's been fixed. It shouldn't be relevant here, but I figure I should mention it.
Upvotes: 5
Reputation: 532153
If you aren't committed to those exact arguments or order of arguments, two options are
>>> [(^ 2), pred] <*> pure 4
[16, 3]
>>> fmap ($ 4) [(^ 2), pred]
[16, 3]
Upvotes: 1
Reputation: 67547
Here is an alternative with sequence
> mmap = map . sequence
> mmap [(^2), pred] [1..3]
[[1,0],[4,1],[9,2]]
Upvotes: 4