问题
In one module I have a user defined type and a recursive function that returns a string. Then I want to create a function that will create an object of that type and pass it to the function. Here is a simple example of the code I have:
type species =
Animal of string
| Mammal of species
| Fish of species
let rec species_to_string = function
| Animal (x) -> x
| Mammal (x) -> "Mammal (" ^ (species_to_string x) ^ ")"
| Fish (x) -> "Fish (" ^ (species_to_string x) ^ ")"
let process () =
let dog = Mammal(Animal("Dog"))
let dogstring = species_to_string dog
print_string dogstring
However when I try to compile this, I receive the error:
File "test.ml", line 13, characters 1-4:
Error: Syntax error
where line 13 is the second last line in my example above.
My code doesn't seem to be the issue. When I change the code to this:
type species =
Animal of string
| Mammal of species
| Fish of species;;
let rec species_to_string = function
| Animal (x) -> x
| Mammal (x) -> "Mammal (" ^ (species_to_string x) ^ ")"
| Fish (x) -> "Fish (" ^ (species_to_string x) ^ ")";;
let dog = Mammal(Animal("Dog"));;
let dogstring = species_to_string dog;;
print_string dogstring;;
it compiles and runs correctly. But I need to put the last 3 lines in a function so it can be called by another module. What am I doing wrong?
回答1:
You need to say
let dog = Mammal(Animal("Dog")) in
let dogstring = species_to_string dog in
print_string dogstring
That is, you need to use the keyword in.
Longer explanation: there are two different uses of let in OCaml. At the top level of a module it defines the contents of the module. This is the case for your definitions of species_to_string and process. In these cases it appears without in.
In all other cases (inside the outermost definitions) the only allowed form is let var = expr in expr. I.e., the in keyword is required.
Having two different uses for let is confusing, there's no question. But once you get used to it it's OK.
来源:https://stackoverflow.com/questions/36414762/ocaml-call-function-within-another-function