Search code examples
schemelispracketmit-scheme

printing pairs from a list in scheme


I'm trying to print pairs from one list kinda like a subset in scheme but with two elements just like this

(1 2 3 4 5)

((1 2) (1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 4) (3 5) (4 5))

the code I wrote doesn't work

(define (subset x) 
(if ( null? x) x
    (map cons x (subset (cdr x)))))

this just return an empty list


Solution

  • I prefer to write the lambdas explicitly, makes it easier to understand what arguments are passed:

    (define subset
        (lambda (lst)
            (if (null? lst)
                lst
                (append (map (lambda (el) (cons (car lst) el)) (cdr lst))
                        (subset (cdr lst)))
            )))
    

    (subset '(1 2 3 4 5))
    => ((1 . 2) (1 . 3) (1 . 4) (1 . 5) (2 . 3) (2 . 4) (2 . 5) (3 . 4) (3 . 5) (4 . 5))
    

    EDIT: The explanation about map below is only valid in some versions of scheme, read Sylwester's comment to this answer.

    map traverses n lists supplied to it and applies proc to the n elements in the same position in the lists. This means it can apply proc no more times than the length of the shortest list, but you keep giving it an empty list (from the last recursive call backwards).

    (BTW this is in plain scheme)