[英]List Recursion in Functional Programming F#
I am writing a recursive function move that takes two lists and inserts the elements from the first list to the second list in reverse order.. 我正在编写一个递归函数移动 ,它需要两个列表并将元素从第一个列表以相反的顺序插入到第二个列表中。
we have a predefined list datatype 我们有一个预定义的列表数据类型
type ilist = E | L of int * ilist
For example: 例如:
move L(2, L(3, E)) L(1, L(2, E))
would give me 会给我
L(3, L(2, L(1, L(2))))
I think i am having syntax errors with my code. 我认为我的代码存在语法错误。 Also not sure if i can prepend using cons since it is a pre-defined list datatype.
也不确定我是否可以使用cons作为前缀,因为它是预定义的列表数据类型。 Any help is appreciated!
任何帮助表示赞赏!
let rec move l r =
match l with
| E -> []
| L(h,E) -> h::r
| L(h,t) -> move t r
There are a couple of syntactic errors and type checking errors in your function. 函数中有一些语法错误和类型检查错误。 You need to indent things properly and parenthesize the arguments of your sample call.
您需要正确缩进内容,并在样本调用的参数中加上括号。 Since you want to return the existing list, which is of type
ilist
, you also need to replace []
and ::
in your right hand side implementation with your constructors L
and E
. 由于要返回现有列表(类型为
ilist
,因此还需要在右侧实现中用构造函数L
和E
替换[]
和::
。 Fixing the issues gives: 解决问题可以得到:
let rec move l r =
match l with
| E -> E
| L(h,E) -> L(h, r)
| L(h,t) -> move t r
move (L(2, L(3, E))) (L(1, L(2, E)))
This runs, but it does not quite do the right thing. 这可以运行,但并不能完全正确。 To actually get this to do what you want, you need to:
要实际使此功能执行您想要的操作,您需要:
move E (L(1, E))
you should get back L(1, E)
but your implementation just returns E
. move E (L(1, E))
,则应返回L(1, E)
但实现仅返回E
You need to return r
. r
。 h
so it will get dropped. h
因此它将被丢弃。 You need to append this to the r
value or the result of the recursive call using the L
constructor. L
构造函数将此值附加到r
值或递归调用的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.