Haskell 将一个函数应用于列表中的每个元素,并应用于另一个列表中的每个元素
我想要一种更优雅的方式来编写以下两个函数,最好是一个函数:Haskell 将一个函数应用于列表中的每个元素,并应用于另一个列表中的每个元素,haskell,Haskell,我想要一种更优雅的方式来编写以下两个函数,最好是一个函数: applyOperatorBetweenVariableLists:: [Variable] -> String -> [Variable] -> [Variable] applyOperatorBetweenVariableLists firstList operator secondList = concat $ map (test firstList operator) secondList test:: [V
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
applyOperator变量之间的声明是:
applyoperatorbetween-variables::Variable->String->Variable->[Variable]
我很确定一定有一个Prelude函数可以做到这一点,或者是一种非常优雅的编写方法。这可以通过do
块简洁地完成:
applyOperatorBetweenVariableLists firstList operator secondList = do
secondVariable <- secondList
firstVariable <- firstList
applyOperatorBetweenVariables secondVariable operator firstVariable
根据该定义,应该清楚地知道如何将其更改并简化为ApplyOperatorBetween VariableList=liftA2。ApplyOperatorBetween Variables
只需对其和ApplyOperatorBetween Variables
的参数重新排序即可,谢谢。我注意到它遗漏了一个concat。有一个实用的解决方案,即flip applyOperator operator secondList firstList
。如果您使用ApplicativeDo
,这可能就是阻止去糖的目的。@chepner这不是和我原来的错误答案有同样的问题,因为它会创建一个额外的嵌套层吗?也许我误解了输出应该是什么(特别是因为我的建议与liftA2
相同,只是拼写不同)。但是你的do
块不是也一样吗,特别是在使用ApplicativeDo
的情况下?我认为,使用test
会产生额外的嵌套层,而你的更新解决方案忽略了这一层。
import Control.Applicative (liftA2)
applyOperatorBetweenVariableLists firstList operator secondList = liftA2 (flip applyOperatorBetweenVariables operator) secondList firstList