Skip to content

Instantly share code, notes, and snippets.

@KMConner
Last active November 6, 2017 04:33
Show Gist options
  • Save KMConner/a2315e20c7c1f5deb4a05fe707808cf5 to your computer and use it in GitHub Desktop.
Save KMConner/a2315e20c7c1f5deb4a05fe707808cf5 to your computer and use it in GitHub Desktop.
OCaml に関するメモ

Install

Windows

なんか色々ややこしい...

Bash on Ubuntu on Windows なら簡単

Ubuntu (Bash on Ubuntu on Windows)

sudo apt-get install opam
opam init

macOS

brew install ocaml
brew install opam
opam init

最後に "Do you want OPAM to modify ~/.bash_profile and ~/.opaninit ?" と聞かれるので y で答える

できたら ocaml -version でインストールされていてパスが通っていることを確認する。

念のため ocamlopt -v も確認する(ネイティブコードへのコンパイラ)

Memo

キャスト色々

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_endlineprerr_endline) エラー出力になる。

match のネスト

beginend で挟む

match t with
  A -> true
| B -> false
| _ ->
    begin
        match ...
    end

コンストラクラ付きのヴァリアントでの match

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

パラメーターの名前は揃える必要がある(たぶん)

if 式の扱い

例えば 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();; としてしまうとエラーとなる。

Structure の定義方法

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)"

先頭の # も入力すること

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment