简体   繁体   中英

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 ?

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;

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]

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM