views:

303

answers:

3

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?

Thanks! :-)

+4  A: 

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

List.tl: 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.hd sample;;

val it : int = 1

> List.tl sample;;

val it : int list = [2; 3; 4]
CMS
+6  A: 

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;
simonuk
+2  A: 

I'm going to have to agree with simonuk. Although, like CMS has mentioned, hd and tl are the correct functions, there is more to the argument then that.

When using pattern matching you can exploit the compilers ability to catch (base) cases you may have missed (such as when the list is empty). You can definitely catch or continue to throw that exception, but you don't have to and you might introduce bugs if that expectation doesn't happen often. So getting in the habit of exploiting the pattern matching is a good programing practice. For all intents and purposes the actual function being applied when calling hd/tl IS matching a pattern. Actually, in ocaml, it is a failure:

let hd = function [] -> failwith "hd" | a::l -> a
let tl = function [] -> failwith "tl" | a::l -> l

As an example, instead of using exceptions/failures we might find it more satisfactory to use options:

> let car = function | hd::tl -> Some hd | _ -> None
> let cdr = function | hd::[] -> None | hd :: tl -> Some tl | _ -> None

Also, be wary of using _ to match anything. It hurts more in variant types when you decide to add another type... opps!

nlucaroni