lisp - Scheme Function to reverse elements of list of 2-list -
this exercise eopl. procedure (invert lst) takes lst list of 2-lists , returns list each 2-list reversed.
(define invert (lambda (lst) (cond((null? lst ) '()) ((= 2 (rtn-len (car lst))) ( cons(swap-elem (car lst)) (invert (cdr lst)))) ("list not 2-list")))) ;; auxiliry procedure swap-elements of 2 element list (define swap-elem (lambda (lst) (cons (car (cdr lst)) (car lst)))) ;; returns lengh of list calling (define rtn-len (lambda (lst) (calc-len lst 0))) ;; calculate length of list (define calc-len (lambda (lst n) (if (null? lst) n (calc-len (cdr lst) (+ n 1)))))
this seems work looks verbose. can shortened or written in more elegant way ? how can halt processing in of individual element not 2-list? @ moment execution proceed next member , replacing current member "list not 2-list" if current member not 2-list.
the eopl language provides eopl:error
procedure exit error message. introduced on page 15 of book (3rd ed.).
the eopl language include map
procedure standard scheme. though may not used in book, can still use shorter solution 1 explicit recursion. can use scheme's standard length
procedure.
#lang eopl (define invert (lambda (lst) (map swap-elem lst))) ;; auxiliary procedure swap-elements of 2 element list (define swap-elem (lambda (lst) (if (= 2 (length lst)) (list (cadr lst) (car lst)) (eopl:error 'swap-elem "list ~s not 2-list~%" lst))))
Comments
Post a Comment