Get the middle elements from List in scheme

情到浓时终转凉″ 提交于 2019-12-04 05:27:40

问题


I'm new to scheme , can someone please give me ideas on how to get , "the middle element from a list?"


回答1:


Here's my solution. It's based on a tortoise-and-hare algorithm (which is used in any kind of list traversal where you need to detect circular lists), so it doesn't do any more work than a sane list traversal has to do anyway. :-)

(define (middle-elements lst)
  (if (null? lst) '()
      (let loop ((tortoise lst)
                 (hare (cdr lst)))
        (cond ((eq? tortoise hare) #f)
              ((null? hare) (list (car tortoise)))
              ((null? (cdr hare)) (list (car tortoise) (cadr tortoise)))
              (else (loop (cdr tortoise) (cddr hare)))))))

It covers the following cases:

  • If given an empty list, returns an empty list.
  • If given a list with an odd number of elements, returns a singleton list with the middle element.
  • If given a list with an even number of elements, returns a list with the two middle elements.
  • If given a circular list, returns #f.
  • If given an improper list (including a non-list), summons nasal demons.


来源:https://stackoverflow.com/questions/13306626/get-the-middle-elements-from-list-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!