なんか色々ややこしい...
Bash on Ubuntu on Windows なら簡単
sudo apt-get install opam
opam init
brew install ocaml
brew install opam
opam init
最後に "Do you want OPAM to modify ~/.bash_profile and ~/.opaninit ?" と聞かれるので
y
で答える
できたら
ocaml -version
でインストールされていてパスが通っていることを確認する。
念のため ocamlopt -v
も確認する(ネイティブコードへのコンパイラ)
string_of_int(334);; (* int -> string *)
int_of_string("334");; (* string -> int *)
int_of_float(1.0);; (* float -> int *)
float_of_int(1);; (* int -> float *)
print_char('a');; (* char を表示 *)
print_int(123);; (* int を表示 *)
print_float(3.14);; (* float を表示 *)
print_string("Hello World");; (* string を表示 *)
print_endline("Hello World");; (* string を表示 + 改行 *)
print_newline();; (* 改行文字 + バッファのフラッシュ *)
それぞれの関数の print を prerr にすると、
(例:print_endline
→ prerr_endline
)
エラー出力になる。
begin
と end
で挟む
match t with
A -> true
| B -> false
| _ ->
begin
match ...
end
例
type calender = Date of int * int * int
| Time of int * int * int
| DayOfWeek of string;;
これが基本
let to_str(dt) =
match dt with
Date(y, m, d) ->
string_of_int(y) ^ "/" ^ string_of_int(m) ^ "/" ^
string_of_int(d)
| Time(h, m, s) ->
string_of_int(h) ^ ":" ^ string_of_int(m) ^ ":" ^
string_of_int(s)
| DayOfWeek(s) ->
s
;;
コンストラクタの引数の数が同じ時は共通化できる
let to_str(dt) =
match dt with
Date(a, b, c) | Time(a, b, c) ->
string_of_int(a) ^ " " ^ string_of_int(b) ^ " " ^
string_of_int(c)
| DayOfWeek(s) ->
s
;;
パラメーターの名前は揃える必要がある(たぶん)
例えば
bool
を受けて string
を返す関数で、
入力値が true
の時は
The value is true!
false
の時は
The value is false!
と返したい時は
let str(t) =
"The value is " ^ if t then "true" else "false" ^ "!";;
ではNG
str(true)
とした時に "The value is true" と帰ってくる ("!" がない)
正しくは
let str(t) =
"The value is " ^ (if t then "true" else "false") ^ "!";;
または
let str(t) =
"The value is " ^
begin
if t then "true" else "false"
end ^
"!";;
(演算子の評価順の関係???)
(*コメント*)
複数行に跨っても構わない
1行だけコメントアウトはなさそう
ターミナルで ocaml
を実行するとインタラクティブでの実行が可能だが、終了は
#quit;;
"#" を忘れたり #quit();;
としてしまうとエラーとなる。
type calender =
Time of time | Date of date | DayOfWeek of string
and time={
hour:int;
minute:int;
second:int;
}
and date={
year:int;
month:int;
day:int;
}
;;
#use "(ファイル名.ml)"
先頭の # も入力すること