Return a list without the last element

  • A+
Category:Languages

I've just started to learn Racket.

I have this code:

#lang racket  (define l1 '(1 2 3 4)) (car l1) (cdr l1) 

(car l1) returns 1.
(cdr l1) returns '(2 3 4)

Is there a function that returns '(1 2 3)?

I've tried this:

#lang racket  (define l1 '(1 2 3 4)) (map  (lambda (l i)    (if (not (= i (sub1 (length l1)))) l '()))  l1 (range 0 (length l1))) 

But, it returns: '(1 2 3 ())

And I have also tried:

#lang racket  (define l1 '(1 2 3 4)) (map  (lambda (l i)    (cond ((not (= i (sub1 (length l1)))) l )))  l1 (range 0 (length l1))) 

But, it returns: '(1 2 3 #<void>)

 


The map function always returns a list the same length as its input. You want an output list that is shorter than its input. The function you are looking for is traditionally called but-last:

(define (but-last xs) (reverse (cdr (reverse xs)))) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: