Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

cons* in scheme - how to implement

I tried to implement the cons* (https://scheme.com/tspl4/objects.html#./objects:s44).

Examples:

(cons* '()) -> ()
(cons* '(a b)) -> (a b)
(cons* 'a 'b 'c) -> (a b . c)
(cons* 'a 'b '(c d)) -> (a b c d)

this is what I did do far but I don't know how to replace the ?? to make the third example (the dot notion) work

   (define cons*
  (lambda x
    (if
     (null? x)
     x
     (if (list? (car (reverse x)))
         (fold-right cons (car (reverse x)) (reverse (cdr (reverse x))))
         ???
      )
     )
    )
  )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a lo-fi way using lambda -

(define cons*
  (lambda l
    (cond ((null? l) null)
          ((null? (cdr l)) (car l))
          (else (cons (car l) (apply cons* (cdr l)))))))

Here's a way you can do it using match (Racket)

(define (cons* . l)
  (match l
    ((list) null)                                ; empty list
    ((list a) a)                                 ; singleton list
    ((list a b ...) (cons a (apply cons* b)))))  ; two or elements

Often times patterns and order can be rearranged and still produce correct programs. It all depends on how you're thinking about the problem -

(define (cons* . l)
  (match l
    ((list a) a)                                ; one element
    ((list a b) (cons a b))                     ; two elements
    ((list a b ...) (cons a (apply cons* b))))) ; more

Or sugar it up with define/match -

(define/match (cons* . l)
  [((list)) null]
  [((list a)) a]
  [((list a b ...)) (cons a (apply cons* b))])

All four variants produce the expected output -

(cons* '())
(cons* '(a b))
(cons* 'a 'b 'c)
(cons* 'a 'b '(c d))
'()
'(a b)
'(a b . c)
'(a b c d)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...