繁体   English   中英

将函数应用于列表中的每个元素到另一个列表中的每个元素

[英]Apply a function to every element in a list to every element in another list

我想要一种更优雅的方式来编写以下两个函数,最好是一个:

applyOperatorBetweenVariableLists:: [Variable] -> String -> [Variable] -> [Variable]
applyOperatorBetweenVariableLists firstList operator secondList = concat $ map (test firstList operator) secondList

test:: [Variable] -> String -> Variable -> [Variable]
test firstVariables operator secondVariable = concat $ map (applyOperatorBetweenVariables secondVariable operator) firstVariables

applyOperatorBetweenVariables的声明是:

applyOperatorBetweenVariables:: Variable -> String -> Variable -> [Variable]

我很确定一定有一个 Prelude 函数可以做到这一点,或者是一种非常优雅的编写方式。

这可以用do块简洁地do

applyOperatorBetweenVariableLists firstList operator secondList = do
  secondVariable <- secondList
  firstVariable <- firstList
  applyOperatorBetweenVariables secondVariable operator firstVariable

如果你想更简洁,你可以重新排列applyOperatorBetweenVariableListsapplyOperatorBetweenVariables的参数,然后使用liftJoin2bind2来实现它(就像我下面的最后一句话,但用它代替liftA2 )。


我原来的答案是错误的,因为它留下了一层嵌套(即,应该做一个额外的concatjoin ):

几乎只是liftA2 ,但你的论点是在一个奇怪的顺序。 以下是您如何实现您所写的内容:

import Control.Applicative (liftA2)
applyOperatorBetweenVariableLists firstList operator secondList = liftA2 (flip applyOperatorBetweenVariables operator) secondList firstList

根据该定义,您应该清楚如何将其更改和简化为applyOperatorBetweenVariableLists = liftA2 . applyOperatorBetweenVariables applyOperatorBetweenVariableLists = liftA2 . applyOperatorBetweenVariables只是通过重新排序它的参数和applyOperatorBetweenVariables

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM