2016-04-04 35 views
0

1つのモジュールには、ユーザー定義型と文字列を返す再帰関数があります。次に、その型のオブジェクトを作成して関数に渡す関数を作成します。ここで私が持っているコードの簡単な例です:OCaml:別の関数内で関数を呼び出す

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 

私はこれをコンパイルしようとすると、しかし、私はエラーが表示されます。

ライン13は、上記の私の例の2番目の最後の行である
File "test.ml", line 13, characters 1-4: 
Error: Syntax error 

私のコードは問題ではないようです。私はこれにコードを変更した場合:

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;; 

それがコンパイルされ、正常に動作します。しかし、最後の3行を関数に入れて、別のモジュールが呼び出せるようにする必要があります。私は間違って何をしていますか?

答えて

8

あなたがキーワードinを使用する必要が、ある

let dog = Mammal(Animal("Dog")) in 
let dogstring = species_to_string dog in 
print_string dogstring 

を言う必要があります。

説明:OCamlにはletという2つの異なる用途があります。モジュールの最上位レベルでは、モジュールの内容を定義します。これは、species_to_stringprocessの定義の場合です。このような場合は、inなしで表示されます。

他のすべての場合(最も外側の定義の内側)は、唯一許される形式はlet var = expr in exprです。つまり、inというキーワードが必要です。

letの2つの異なる用途が混乱していることは疑いありません。しかし、一度それに慣れればOKです。

関連する問題