简体   繁体   English

将 function 应用于 Haskell 中的元素列表

[英]Applying a function to a list of elements in Haskell

Say i've defined a Queue and have the following function:假设我定义了一个队列并具有以下 function:

pushq :: a -> Queue a -> Queue a

pushq x (Queue1 xs) = Queue1 (x:xs)

It works by adding a single element it to the front of a queue, but say I wanted to use the function in another method which would add an entire list of elements to a queue rather than a single one such as:它通过将单个元素添加到队列的前面来工作,但是说我想在另一种方法中使用 function 将整个元素列表添加到队列而不是单个元素,例如:

adds :: [a] -> Queue a -> Queue a

How would I be able iterate through the list and use the pushq function on every element one by one to add it to the queue?我如何能够遍历列表并在每个元素上一个一个地使用 pushq function 将其添加到队列中?

How would I be able iterate through the list and use the pushq function on every element one by one to add it to the queue?我如何能够遍历列表并在每个元素上一个一个地使用 pushq function 将其添加到队列中?

Through recursion.通过递归。 For an empty list you can return the Queue a itself:对于空列表,您可以返回Queue a本身:

adds [] qs = qs

for a non-empty list, you first call adds on the tail of the list, and then push that element on the queue:对于非空列表,您首先在列表的尾部调用adds ,然后将该元素推入队列:

adds (x:xs) q = pushq … (adds …)

you still have to fill in the s here.您仍然必须在此处填写 I leave this as an exercise.我把它留作练习。

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

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