Question

I'm new to functional programming, especially Scheme which is the programming language I'm using. I'm still trying to grasp the main concepts of Scheme.

What I'm trying to do, is to write a function in Scheme that takes two chars (a and b, say) and a list of pairs of strings for e.g. '(("one" "two")("three" "four")("five" "six")) as input, and that returns a modified list of pairs of strings: for each string pair in the list. So basically, I need to add a to the front of the first string and b to the front of the second string assuming a and b were the chars received as input.

Here is an example of input/output that I'm trying to achieve:

Input:

(modify-list-pair-of-strings "a" "b" '(("one" "two")("three" "four")("five" "six")))

Output:

'(("aone" "btwo")("athree" "bfour")("afive" "bsix"))

I'm not sure how to go about implementing this. I know I can use some of the common list operations such as car, cons, cdr, etc. but I find it quite confusing.

Was it helpful?

Solution

(define (modify-list-pair-of-strings a b lst)
  (map (lambda (x)
         (list (string-append a (car x))
               (string-append b (cadr x))))
       lst))

Runnable sample here: http://eval.ironscheme.net/?id=132

A more dynamic example:

(define (modify-list-pair-of-strings pre lst)
  (map (lambda (x)
         (map string-append pre x))
       lst))

(modify-list-pair-of-strings 
 '("a" "b" "c") 
 '(("one" "two" "three")("three" "four" "five")("five" "six" "seven")))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top