OCaml:另一个函数中的调用函数 [英] OCaml: Call function within another function
问题描述
在一个模块中,我有一个用户定义的类型和一个返回字符串的递归函数.然后,我想创建一个函数,该函数将创建该类型的对象并将其传递给该函数.这是我拥有的代码的一个简单示例:
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
在上面的示例中,第13行是倒数第二行.
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?
推荐答案
您需要说
let dog = Mammal(Animal("Dog")) in
let dogstring = species_to_string dog in
print_string dogstring
也就是说,您需要使用关键字in
.
That is, you need to use the keyword in
.
更长的解释:OCaml中let
有两种不同的用法.在模块的顶层,它定义了模块的内容.您对species_to_string
和process
的定义就是这种情况.在这些情况下,它似乎没有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
.
在所有其他情况下(在最外面的定义内),唯一允许的形式是let var = expr in expr
.也就是说,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.
let
有两种不同用途,这令人困惑,这是毫无疑问的.但是一旦习惯了就可以了.
Having two different uses for let
is confusing, there's no question. But once you get used to it it's OK.
这篇关于OCaml:另一个函数中的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!