简体   繁体   English

函数式编程F#中的列表递归

[英]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 ,因此还需要在右侧实现中用构造函数LE替换[]:: 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: 要实际使此功能执行您想要的操作,您需要:

  • In the first case, if you call 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
  • In the last case, you are not using 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值或递归调用的结果。
  • You also do not need the second case - if you get things right, the first and the last cases will cover all options you need. 您也不需要第二种情况-如果您做对了,则第一种和最后一种情况将涵盖您需要的所有选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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