By your indentation alone, it's very evident that you're coming to Scheme from another programming language
But you're also using if
incorrectly – in Scheme, you cannot have a single-branch if
statement. Well, there's no statements in Scheme at all, only expressions, and if
expressions will always take 3 operands (arguments)
- the predicate (condition)
- the consequent (what happens if the predicate is true)
- the alternative (what happens when the predicate is false)
Your program is close tho. Just a little adjustment and you're right where you need to be – take note of how the indentation makes it easy to see if
's 3 operands.
(define (last mylist)
(if (null? mylist)
#f
(if (null? (cdr mylist))
(car mylist)
(last (cdr mylist)))))
Lastly, Scheme offers cond
that helps prevent unnecessary code nesting for sequences of conditions
(define (last mylist)
(cond ((null? mylist)
#f)
((null? (cdr mylist))
(car mylist))
(else
(last (cdr mylist)))))
(last '())
;; #f
(last '(1))
;; 1
(last '(1 2))
;; 2
(last '(1 2 3))
;; 3
Beyond the scope of this answer is the return value #f
for (last '())
– I would argue that calling last
on an empty list should have the same effect of calling car
on an empty list. But I'll leave it up to you.
if
expression, if(null? (cdr mylist))
is true, you should returns(car mylist)
instead of an empty list'()
. – Pie 'Oh' Pah