简体   繁体   中英

List manipulation with foldr in Racket

#lang racket

I need to create a list from 2 lists

list1 => '(1 2 3)
list2 => '(a b c)

desired result of

(define (create-list l1 l2)
...
)

to be '((1 a) (2 b) (3 c))

must use foldr and cannot use recursion.

I was thinking about running a counter and using list-ref, is there a better way ?

In Racket, the foldr higher-order procedure can take multiple lists as arguments, you just have to craft a lambda that processes them as required:

(define (create-list l1 l2)
  (foldr (lambda (e1 e2 acc)
           (cons (list e1 e2) acc))
         '() l1 l2))

For example:

(create-list '(1 2 3) '(a b c))
=> '((1 a) (2 b) (3 c))

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