How do I make a car and frame against a list?

Suppose I have code:

let listB = [ 1; 2; 3 ] 

Using Lisp notation, how do I make car and cadr against this list? I know the minus :: .

Or in the scheme, first and rest ?

+4
source share
3 answers

List.head: returns the first element of a non-empty list (the head of the list).

List.tail: returns all the elements of a non-empty list except the first (tail or remainder of the list).

Example (using the 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] 
+5
source

List.hd and List.tl will do what you want, but in F # you will find that lists are usually deconstructed using pattern matching. For example, in the following function, x corresponds to head and xs corresponds to 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; 
+6
source

I need to agree with simonuk. Although, as mentioned in the CMS, hd and tl are the correct functions, there are more arguments in this case.

When using pattern matching, you can use the compiler features to catch (basic) cases that you might have missed (for example, when the list is empty). You can probably catch or continue throwing this exception, but you do not need this, and you can introduce errors if this expectation does not occur often. Therefore, the habit of using pattern matching is good programming practice. For all purposes and tasks, the actual function is used when calling hd / tl IS that matches the pattern. In fact, in oamaml this 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 / crashes, we may find it more acceptable to use options :

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

Also, be careful when using _ to match anything. It hurts more in options when you decide to add another type ... opps!

+2
source

All Articles