在其他函数ocaml中处理递归函数 [英] Handle recursive function within an other function ocaml
问题描述
如果我在Ocaml函数内部有一个或多个递归函数,如何在不退出主函数的情况下调用它们,而将它们的值作为主函数的返回值? 我是Ocaml的新手,所以我会尽力向我解释一下...
If I have one or more recursive functions inside an Ocaml function how can I call them without exit from the main function taking their value as return of the main function? I'm new in Ocaml so I'll try to explain me better...
如果我有:
let function =
let rec recursive1 = ...
...
let rec recursive2 = ...
...
如何在function
中称呼它们为嘿,您看到此递归函数了吗?现在调用它并获取其价值."
因为我的问题是作为函数返回的Ocaml看到了Unit
而不是正确的返回.
我将在下面发布代码:
How can I call them inside function
to tell it "Hey, do you see this recursive function? Now call it and takes its value."
Because my problem is that Ocaml as return of my functions sees Unit
instead of the right return.
I will post the code below :
let change k v list_ =
let rec support k v list_ =
match list_ with
| [] -> []
| (i,value) :: tl -> if i = k
then (k,v) :: tl
else (i,value) :: support k v tl in
let inserted = support k v list_ in inserted
let () =
let k = [ (1,"ciao");(2,"Hola");(3,"Salut") ] in
change 2 "Aufwidersen" k
Change
将一个键,一个值和一个(int * string )list
作为输入,并应返回输入的相同列表,但更改链接到所选key
的值(如果在list中).
相反,support
使该工作变脏.它会建立一个新列表,并在找到i = k
的k时将其更改为value
并附加图块,从而关闭该函数.
Change
takes as input a key, a value and a (int * string )list
and should return the same list of the input but changing the value linked to the key
selected ( if in list ).
support
, instead, makes the dirty job. It builds a new list and when k is found i = k
it changes value
and attach the tile, closing the function.
change
的返回值应为(int * string) list
时为unit
.我认为是因为inserted
不被视为函数的返回.
The return of change
is unit
when it should be (int * string) list
. I think because inserted
isn't taken as return of the function.
推荐答案
change
不返回unit
.实际上,该错误告诉您的情况恰恰相反,它返回(int * string) list
,但是期望为unit
.它期望单位,因为您正在将其分配给()
模式.
change
does not return unit
. The error in fact tells you exactly the opposite, that it returns (int * string) list
but that it expects unit
. And it expects unit because you're assigning it to a ()
pattern.
我不知道您实际上打算如何使用返回值,因为现在您似乎并不在乎它,但是您可以通过将错误赋值给一个名称来解决该错误:
I don't know what you actually intend to do with the return value, as right now you don't seem to care about it, but you can fix the error by just assigning it to a name:
let result: (int * string) list =
let k = [ (1,"ciao");(2,"Hola");(3,"Salut") ] in
change 2 "Aufwidersen" k
由于未使用它,所以我添加了一个类型注释,以确保我们得到了我们期望的结果,否则,result
可以是任何东西,并且编译器不会抱怨.但是,如果要使用result
,通常就不需要此选项,因为如果类型与用法不统一,则会出现错误.
Since it's not used I've added a type annotation to make sure we're getting what we expect here, as otherwise result
could be anything and the compiler wouldn't complain. You don't typically need this if you're going to use result
however, as you'd then get an error if the type doesn't unify with its usage.
这篇关于在其他函数ocaml中处理递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!