我在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))
由于您具有自定义列表定义,因此标准的“头尾”功能不起作用。您可以使用模式匹配来创建自己的函数,该模式与您沿途走的路线相似:
let myHead xs =
match xs with
| NIL -> None
| CONS(h, _) -> Some(h)
let myTail xs =
match xs with
| NIL -> None
| CONS(_, t) -> Some(t)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句