简体   繁体   English

在 Haskell 中的两个列表上使用变量二进制操作

[英]Using variable binary operation on two lists in Haskell

I'm trying to write a program that takes in two lists and a binary operation and takes each element of one list and applies it to the other using the binary operation.我正在尝试编写一个程序,该程序接受两个列表和一个二进制操作,并获取一个列表的每个元素并使用二进制操作将其应用于另一个列表。 I have it working but not sure how to change it so it works with any binary operator.我让它工作,但不知道如何改变它,所以它适用于任何二元运算符。 Here's examples:以下是示例:

myFunction (+) [100,200,300] [4,3,2,1] would return
[96,97,98,99,196,197,198,199,296,297,298,299]

myFunction (+) [100,200,300] [4,3,2,1] would return
[96,97,98,99,196,197,198,199,296,297,298,299]

This is what I have working with specific binary operations这就是我使用特定二进制操作所做的工作

The simplest way is a list comprehension:最简单的方法是列表推导:

myFunction f xs ys = [f x y | x <- xs, y <- ys]

It may not even be worth defining a new function;甚至可能不值得定义一个新的 function; instead, just inline that content to the call site.相反,只需将该内容内联到调用站点。

This function is also available from the standard library by the names liftM2 and liftA2 .这个 function 也可以从标准库中以名称liftM2liftA2

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

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