As part of my assignment i have been given the task to:
Write a function that takes two lists as input, a list L1 containing characters and a list L2
containing numbers. For each of the number n contained in L2, the function will display the first
n character of the list L1. For example:
L1 '("h" "e" "l" "l" "o" "w" "o" "r" "l" "d")
L2 '(2 3 1 5 10)
Output:
h e
h e l
h
h e l l o
h e l l o w o r l d.
i know the function takes two arguments but i don't know how to apply the second the list which is like a selector,it reads each number in the second list and extracts the character in that position in the first list.
( define two-sequences
( lambda ( l1 l2 )
(for/list ([ i l1 ] [ j l2 ])
which function should i use to do this.
CodePudding user response:
You need to print the first n elements of a list. Here's how you do that:
To print the first n
elements of a list, lst
:
- if
n
is zero print a newline; - if
n
is 1 print the first element oflst
and a newline; - if
n
is more than 1 print the first element of thelst
, a space, and then printn - 1
elements of the rest oflst
(hint: you can use a function you are currently writing to do this); - if
n
is anything else then this is an error.
Write this as a proceducre: call it print-n
for instance. Then the procedure which answers the question is:
(define (print-ns l ns)
(for ([n (in-list ns)])
(print-n l n)))
And
> (print-ns '("h" "e" "l" "l" "o" "w" "o" "r" "l" "d") '(2 3 1 5 10))
h e
h e l
h
h e l l o
h e l l o w o r l d
CodePudding user response:
In Common Lisp or emacs lisp this function you want is called elt
which gives the nth element of a list. - In Racket, you have to define it yourself:
(define (elt l n)
(cond ((empty? l) '())
((zero? n) (car l))
(else (elt (cdr l) (- n 1)))))
(elt '(a b c d e f) 3) ;;=> 'd
In every-day racket, however, one wouldn't use lists - which one has to traverse like this - but vectors - whose access via an index is direct and thus much more faster.
(vector-ref #("a" "b" "c" "d" "e" "f") 3) ;;=> "d"
#(...)
is equal to (vector ...)
and creates a vector out of the sequence.