[英]Haskell: Print elements of a list
I have a list let a = [1,2,3,4]
我有一个列表,
let a = [1,2,3,4]
I want to extract 2 elements at a time to perform computation. 我想一次提取2个元素来执行计算。 Can anyone tell me how this can be achieved?
谁能告诉我如何实现? I am new to Haskell.
我是Haskell的新手。
I am aware of take 2 a
. 我知道
take 2 a
。 But how can I put this in a loop so that 2 elements are extracted at a time. 但是如何将其循环放置,以便一次提取2个元素。 I am confused.
我很困惑。
Here's an example. 这是一个例子。 You are (or should become) familiar with the
map
function: 您(或应该)熟悉
map
函数:
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
Here, you might have a function that takes two arguments, and want to apply it to two elements from a list at a time. 在这里,您可能有一个接受两个参数的函数,并且希望一次将其应用于列表中的两个元素。 Here's a function
mapTwo
that behaves like map
, but with a two-argument function. 这是一个函数
mapTwo
,其行为类似于map
,但具有两个参数的函数。 For simplicity, we'll assume the list has an even number of elements. 为简单起见,我们假定列表中的元素数为偶数。
mapTwo :: (a -> a -> b) -> [a] -> [b]
mapTwo f [] = []
mapTwo f (x1:x2:xs) = f x1 x2 : mapTwo f xs
You can write your own recursive function and pattern-match on elements you are interested in: 您可以在感兴趣的元素上编写自己的递归函数和模式匹配:
f (a:b:list) = doSomeThingWith a b : f list
Make sure to properly match on []
and [a]
cases. 确保在
[]
和[a]
情况下正确匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.