开发者

Map a function over a list for each argument

I'开发者_Python百科m looking for some attractive Haskell syntax for the following

I have a function that takes 4 argument.

f a b c d = Something

I'd like to supply a lists for each of the arguments and get back the a list of the results of each combination.

Essentially a nested map function.

I fell like there should be an elegant solution. But, I haven't found anything that will compile.


Your question is not very clear: do you want all possible combinations (take any a from the first list, any b from the second etc.) or processing lists in parallel a.k.a. zip (the first element of each list, the second element and so on).

Both can be nicely solved with applicative functors:

Prelude> let f a b c d = (a,b,c,d)
Prelude Control.Applicative> :m +Control.Applicative 
Prelude Control.Applicative> f <$> [1,2] <*> [3,4] <*> [5,6] <*> [7,8]
[(1,3,5,7),(1,3,5,8),(1,3,6,7),(1,3,6,8),(1,4,5,7),(1,4,5,8),(1,4,6,7),(1,4,6,8),(2,3,5,7),(2,3,5,8),(2,3,6,7),(2,3,6,8),(2,4,5,7),(2,4,5,8),(2,4,6,7),(2,4,6,8)]
Prelude Control.Applicative> getZipList $ f <$> ZipList [1,2] <*> ZipList [3,4] <*> ZipList [5,6] <*> ZipList [7,8]
[(1,3,5,7),(2,4,6,8)]


I think I get what you are looking for:

fourway f as bs cs ds = map (curry4 f) [(r,s,t,u) | r <- as, s <- bs, t <- cs, u <- ds]
where curry4 f (a,b,c,d) = f a b c d

You could do this point free and be cuter but I think this is what you want and is easier to read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜