将函数映射到每个参数的列表上

发布于 2024-10-19 02:45:17 字数 176 浏览 1 评论 0原文

我正在寻找一些有吸引力的 Haskell 语法,

我有一个需要 4 个参数的函数。

fabcd =

我想为每个参数提供一个列表,并返回每个组合的结果列表。

本质上是一个嵌套的映射函数。

我觉得应该有一个优雅的解决方案。但是,我还没有找到任何可以编译的东西。

I'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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等数载,海棠开 2024-10-26 02:45:17

您的问题不是很清楚:您是否想要所有可能的组合(从第一个列表中获取任何 a ,从第二个列表中获取任何 b 等)或并行处理列表zip(每个列表的第一个元素,第二个元素,依此类推)。

两者都可以通过应用函子很好地解决:

Prelude> let f a b c d = (a,b,c,d)
Prelude Control.Applicative> :m +Control.Applicative 
Prelude Control.Applicative> f <
gt; [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 <
gt; ZipList [1,2] <*> ZipList [3,4] <*> ZipList [5,6] <*> ZipList [7,8]
[(1,3,5,7),(2,4,6,8)]

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 <
gt; [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 <
gt; ZipList [1,2] <*> ZipList [3,4] <*> ZipList [5,6] <*> ZipList [7,8]
[(1,3,5,7),(2,4,6,8)]
清引 2024-10-26 02:45:17

我想我明白你在寻找什么:

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

你可以免费完成这一点并且更可爱,但我认为这就是你想要的并且更容易阅读。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文