Skip to content

Instantly share code, notes, and snippets.

@ijp
Created October 21, 2014 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijp/1388e8b2285e0ac546b7 to your computer and use it in GitHub Desktop.
Save ijp/1388e8b2285e0ac546b7 to your computer and use it in GitHub Desktop.
;;; jffmcc's solution
(define (Last2Equal? L)
(cond ((> (length L) 2) (Last2Equal? (cdr L)))
((= (length L) 2) (equal? (car L) (cadr L)))
(else #f)))
;;; Alternative Solutions
;;; Compute length only once
(define (drop n l)
(if (zero? n)
l
(drop (- n 1) (cdr l))))
(define (last-2-equal? l)
(define len (length l))
;; only compute length once, use it twice
(if (< len 2)
#f
(let ((last-2 (drop (- len 2) l)))
(equal? (car last-2) (cadr last-2)))))
;;; No length computation at all, just list ops
(define (last-2-equal? l)
(cond ((null? l) #f)
((null? (cdr l)) #f) ; length 1
((null? (cddr l)) ; length 2
(equal? (car l) (cadr l)))
(else ; length > 2
(last-2-equal? (cdr l)))))
(last-2-equal? (list 1 2 3 4 4))
(last-2-equal? (list 1 2 3 4 5))
(last-2-equal? (list 2 2))
(last-2-equal? (list 1))
(last-2-equal? (list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment