aboutsummaryrefslogtreecommitdiff
path: root/p99/p06.neb
blob: f2190587f98e52ebc196afb3d1110f1238563fec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
; P06 Find out whether a list is a palindrome.
; A palindrome can be read forward or backward; e.g. (x a m a x).

(def odd-good (list "x" "a" "m" "a" "x")) ; odd number of elements (good)
(def odd-bad (list "x" "f" "m" "a" "x")) ; odd number of elements (bad)
(def even-good (list "a" "b" "b" "a")) ; even number of elements (good)
(def even-bad (list "a" "b" "b" "f")) ; even number of elements (bad)
(def single (list "a")) ; single element
(def empty (list))

(func palindrome? (lst)  ; by convention, funcs returning :bool end with a ?
    (if (< (length lst) 2)  ; 0 or 1 element lists are palindromic
        #true
        (and
            (eq? (first lst) (last lst))  ; first element and last element are equal
            (palindrome? (most (rest lst))))))  ; this would be clearer if slices supported negative numbers

(print (->string (palindrome? odd-good)))
(print (->string (palindrome? odd-bad)))
(print (->string (palindrome? even-good)))
(print (->string (palindrome? even-bad)))
(print (->string (palindrome? single)))
(print (->string (palindrome? empty)))