Benjamin Creem
Benjamin Creem

Reputation: 95

If I have a custom defined list type in F#, how do I get the head and tail of a list of that type

I have a custom defined list in F# such as:

type 'element mylist = NIL | CONS of 'element * 'element mylist

And I want to reverse a list of this type using something similar to

let rec helperOld a b =
    match a with
    | [] -> b
    | h::t -> helperOld t (h::b)

let revOld L = helperOld L []

What I've thought to do so far is to do something like

let rec helper a b = 
    match a with
    | NIL -> b
    | CONS(a, b) -> helper //tail of a, head of a cons b

However I am having trouble figuring out how to get the tail and head of a. The standard a.Head and a.Tail don't work. How can I access those elements in this custom defined list?

Upvotes: 1

Views: 499

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

Your helper function doesn't need to use Head or Tail functions because it can pull those values out with pattern matching:

let rec helper a b = 
    match a with
    | NIL -> b
    | CONS(x, xs) -> helper xs (CONS(x, b))

The standard Head and Tail functions do not work because you have a custom list definition. You can create your own functions with pattern matching, which is similar to the route you were going down:

let myHead xs =
    match xs with
    | NIL -> None
    | CONS(h, _) -> Some(h)

let myTail xs =
    match xs with
    | NIL -> None
    | CONS(_, t) -> Some(t)

Upvotes: 5

Related Questions