noise

計算機科学や各種設定のメモ

OCamlメモ

alias ocaml='rlwrap -H ~/.ocaml_history -D 2 -i -s 10000 ocaml'
x + y + z

t0 = x + y
t1 = t + z

みたいなかんじに

    • A正規化
      • let の入れ子を無くす
    • CPS変換
      • CPS形式に変換。例外呼出や末尾呼出が最適化しやすくなる。
  • findlib
    • インストールするとREPLの拡張やocamlfindコマンドの追加が行われる
    • ocamlfind の引数にコンパイルコマンド(ocamlc|ocamlopt 〜)を与えるとリンクするライブラリをいちいち列挙せずにすむ
  • 高速化用オプション 参考1 参考2
ocamlopt -unsafe -ccopt -O9 -noassert -inline<n> -ffast-math
let fastInvSqrt x =
  let xhalf = 0.5 *. x in
  let i = Int32.bits_of_float x in
  let t = Int32.sub 0x5f3759dfl (Int32.shift_right_logical i 1) in
  let r = Int32.float_of_bits t in r *. (1.5 -. xhalf *. r *. r);;
fun x -> x |> float |> sqrt |> Float.to_int

fun x -> Float.to_int (sqrt (float x))

と等価

let rec fact n = if n = 1 then 1 else n * (fact (n-1))

はOK

let rec x = x
let rec x = 1 + x

はNG
違いは定義しようとしている変数が他の関数に適用されるかどうか。

#load "gtkInit.cmo";;
    • とすれば動く ocamlc の場合 gtkInit.cmx をリンクする必要がある
ocamlfind ocamlopt -package lablgtk2 -linkpkg gtkInit.cmx test_gtk.ml -o test_gtk

Batteries と スレッド環境でのコンパイル

ocamlfind ocamlopt -thread -package lablgtk2 -package batteries -linkpkg gtkInit.cmx test_gtk.ml -o test_gtk
  • ContinuationPassingStyle in OCaml
# let id x = x
# let rec fact n c =
  if n < 2 then c 1 else fact (n-1) (fun x -> c (n * x));;
# let rec fib n c = if n < 2 then c 1 else fib (n-1) (fun x -> c (x + fib (n-2) id))