简体   繁体   中英

Applying a function to a list of elements in Haskell

Say i've defined a Queue and have the following 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:

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?

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?

Through recursion. For an empty list you can return the Queue a itself:

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 (x:xs) q = pushq … (adds …)

you still have to fill in the s here. I leave this as an exercise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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