Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a car and cadr against a list?

Suppose I have some code:

let listB = [ 1; 2; 3 ]  

Using Lisp notation, how do I do a car and cadr against this list? I know cons is ::.

Or in Scheme, first and rest?

like image 888
Paul Nathan Avatar asked Dec 14 '22 06:12

Paul Nathan


2 Answers

List.hd and List.tl will do what you want - but in F# you will find that lists are typically deconstructed using pattern matching. For example, in the following function x matches the head and xs matches the tail of the list passed to the function:

let list = [1;2;3]

let rec f = function
    | [] -> 1
    | (x::xs) -> x * (f xs)

f list;
like image 61
simonuk Avatar answered Dec 22 '22 03:12

simonuk


List.head: Returns the first element of a nonempty list (The head of the list).

List.tail: Returns all the elements of a nonempty list except the first (The tail or rest of the list).

Example (using F# Interactive Console):

> let sample = [1;2;3;4];;

val sample : int list

> List.head sample;;

val it : int = 1

> List.tail sample;;

val it : int list = [2; 3; 4]
like image 28
Christian C. Salvadó Avatar answered Dec 22 '22 03:12

Christian C. Salvadó