tags:

views:

222

answers:

4

Say I want to take the first item of the lists '(4 3 1) '(5 6 8)

I want something like this

(first '(4 3 1) '(5 6 8))

should return me the first item

(4 3 1)

as result. Is there something like this in scheme build-in function I can call ?

car doesn't work, as it only returns me the first item inside 1 list

list-ref doesn't work, same reason above, returns me 1 item inside the list

How can I do that? if I need to write it myself this first function ?

+1  A: 

It's been a while since I used scheme, but wouldn't you need to have the lists in their own list first

(first (list '(4 3 1) '(5 6 8)))

Kendrick
oh right, good point
Jonathan
No, you don't. You can define a function that takes two parameters, each of which can be a list, and simply return the first one. You'd want to use a list of lists if (for example) you wanted, for some reason, to accept an arbitrary number of lists, and still return only the first of them.
Jerry Coffin
Good point. I was assuming the arbitrary number of lists as part of the requirements.
Kendrick
+3  A: 

You're trying too hard:

> (define (first a b) a)    
> (first '(1 2 3) '(4 5 6))
(1 2 3)
Jerry Coffin
something like that works, but I guess I didn't put my whole problem here. it doesn't work when one of them have no value pass into. But thanks I think i got the idea :)
Jonathan
+2  A: 

You can use the list-ref procedure to get an element from a list, using its index, for example:

(let ((l '((4 3 1) (5 6 8))))
  (list-ref l 0)) ; get the element at index 0

However if you only want the first element, you can use car:

(let ((l '((4 3 1) (5 6 8))))
  (car l))

Check the snippet running here.

CMS
NICE this is awesome
Jonathan
Didn't you just say list-ref didn't work...?
Andrew Song
+3  A: 

You can use "." in function definition to take arbitrary number of arguments.

(define (first . args) (car args))
(first '(4 3 1) '(5 6 8))  ;; => (4 3 1)
torus