问题
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...
If I have :
let function =
let rec recursive1 = ...
...
let rec recursive2 = ...
...
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
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.
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.
回答1:
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
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.
来源:https://stackoverflow.com/questions/62531154/handle-recursive-function-within-an-other-function-ocaml