如果我在 F# 中有自定义列表类型,我如何获取该类型列表的头部和尾部

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

我在 F# 中有一个自定义列表,例如:

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

我想使用类似于

的方法来反转这种类型的列表
let rec helperOld a b =
    match a with
    | [] -> b
    | h::t -> helperOld t (h::b)

let revOld L = helperOld L []

到目前为止,我一直想做的是

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

但是我无法弄清楚如何获取 a 的尾部和头部。标准 a.Head 和 a.Tail 不起作用。如何访问此自定义列表中的那些元素?

您的辅助函数不需要使用 Head 或 Tail 函数,因为它可以通过模式匹配提取这些值:

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

标准的 Head 和 Tail 函数不起作用,因为您有自定义列表定义。您可以使用模式匹配创建自己的函数,这与您走的路线类似:

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

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