4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

金融業界で手堅い支持あり!関数型言語「OCaml」をMacbookに入れてみる

Last updated at Posted at 2020-12-24

簡潔、明瞭! 宣言型のfunctionalプログラミング

( お題1 )
引数の数値が、「素数」(Prime number)であるかどうか評価して、結果をBooleanで返せ

OCaml
ocean@AfoGuardMacBook-Pro ~ % ocaml
        OCaml version 4.11.1

# let is_prime x = 
  	let rec is_divisible_from_2_to n =
  		(n > 1) && ((x mod n = 0) || is_divisible_from_2_to (n-1))
  	in not (is_divisible_from_2_to (x-1));;                                
val is_prime : int -> bool = <fun>
# 
  is_prime 3;;
- : bool = true
# is_prime 73;;
- : bool = true
# is_prime 6431;;
- : bool = false
# is_prime 97;;
- : bool = true
# 

( お題2 )
とっても素敵な言語、OCamlを使って、GAN(Generative Adversarial Network)モデルの重み学習をし、未知データにモデル適用して推論結果を出せ。

(解答例)
以下のGitHubにGANのOCaml実装がある。

(GitHub)LaurentMazare / tensorflow-ocaml

GANモデルのニューラルネットワークの構造を、関数型プラグラミングとして、素直に「宣言」(定義)している。

GANs applied to the MNIST dataset

let create_generator rand_input =

let linear1 = Layer.Linear.create generator_hidden_nodes in
let linear2 = Layer.Linear.create image_dim in
let output =
Layer.Linear.apply linear1 rand_input ~activation:(Leaky_relu 0.01)
|> Layer.Linear.apply linear2 ~activation:Tanh
in
output, (Layer.Linear.vars linear1 @ Layer.Linear.vars linear2)

let create_discriminator xs1 xs2 =
let linear1 = Layer.Linear.create discriminator_hidden_nodes in
let linear2 = Layer.Linear.create 1 in
let model xs =
Layer.Linear.apply linear1 xs ~activation:(Leaky_relu 0.01)
|> Layer.Linear.apply linear2 ~activation:Sigmoid
in
let ys1 = model xs1 in
let ys2 = model xs2 in
ys1, ys2, (Layer.Linear.vars linear1 @ Layer.Linear.vars linear2)

let real_loss = O.binary_cross_entropy ~labels:(O.f 0.9) ~model_values:real_doutput in
let fake_loss = O.binary_cross_entropy ~labels:(O.f 0.) ~model_values:fake_doutput in
let discriminator_loss = O.(real_loss + fake_loss) in
let generator_loss = O.binary_cross_entropy ~labels:(O.f 1.) ~model_values:fake_doutput in

( 以下は省略 )

OCamlは、関数型言語の1つです。

オキャムル -> 岡村 -> ナイナイ岡村 ??

OCaml([oʊˈkæməl] oh-KAM-əl、オーキャムル、オーキャメル)は、フランスの INRIA が開発したプログラミング言語MLの方言とその実装である。MLの各要素に加え、オブジェクト指向的要素の追加が特長である。かつては Objective Caml という名前で、その略として OCaml と広く呼ばれていたが、正式に OCaml に改名された[2]。

え? 関数型言語って。。。Haskellとかのあれ?

それって、稼働かけて習得しても、実用性あるの??

それが、あるんです。

React(ive Programming) ✖️ OCaml == Reason

type schoolPerson = Teacher | Director | Student(string);

let greeting = person =>
  switch (person) {
  | Teacher => "Hey Professor!"
  | Director => "Hello Director."
  | Student("Richard") => "Still here Ricky?"
  | Student(anyOtherName) => "Hey, " ++ anyOtherName ++ "."
  };

Reason を使うと、JavaScript & OCaml の両方のエコシステムを活用しながら、単純、高速かつ高品質な型安全コードを書くことができます。

Facebook の chenglou 氏が作ってる ocaml の言語拡張で、1方言という位置づけです。chenglou氏は react-motion の人というと React界隈では通りがいいと思います。

Reason の一番の特色は ocaml に js っぽいフレーバーの構文にしつつ、React.js の JSX 構文に対応していて、 BuckleScript をバックエンドしながら JS を生成して、 React アプリを簡単に作れるような言語を目指してる、という感じです。勿論、ocaml なので、ネイティブコードを吐くことを出来ます。

ブロックチェーンでも?

ここで1つ、おもしろい通貨を紹介します。「Tezos」というブロックチェーンプロトコルです。これはOCamlで全部書かれているすごいやつなんですよ。OCamlで書かれています。それでTezosという通貨もあるんですね。あまり有名じゃなくてみんな知らないし、普通によくあるところで取引されていないんですけど、そういうものがあるんですよ。それでOCamlで書かれている。

今、パリにいるOCamlerたちがわりと中心となって開発しています。コアの部分は全部OCamlで書かれています。関数型プログラミングと、あとは形式検証ですね。証明を使ってすごい安全なブロックチェーンのプロトコルを実現しようとやっています。これはすごいですね。

さらに日本では、日本にも拠点がありまして京都にキャメロバ様……昔キャメロバ様だったんですけど、今よく見たらキャメロバ様じゃなくなってたので……。

(会場笑)

CamlSpotter、OCaml界隈ではスーパー有名な日本人の人がいるんですけど、その人が中心になって開発しています。さらにガリグ先生とか京大の五十嵐先生たち……これはJavaにジェネリックスを入れたりしているのも有名ですね。主に研究の分類でコミットして、熱い関数型で熱い通貨になっています。

OCamlは、フランスの巨大研究機構 INRIAが開発した関数型言語です。

( 特徴 )

  • Haskellに比べると、「関数型言語」としての「純度」はやや緩和されているもの
  • 金融業界や、「バグが許されない」ミッション・クリティカルな電力システムや航空(機・管制)システムなどで、手堅い採用実績あり

金融業界に根を張る関数型言語、OCaml

Try reading Caml trading - experiences with functional programming on Wall Street by Yaron Minsky and Stephen Weeks (apologies, while this article used to be hosted for free at Jane Capital, it is no longer there, so I leave the ACM link for reference).

( ・・・省略・・・ )

Update: See also the thread What programming language(s) is algorithmic trading software written in?.

Camlは既に様々な方面で応用されている実用言語です。それらの一例を紹介します。

LexiFi
LexiFi?はフランス・パリにあるソフトウェア開発会社の名前であり、金融商品の統合開発環境のブランド名でもあります。彼の金融向けアプリケーションはOCamlやHaskellで作成されています。また、複雑な契約をコンビネーターーから構築できるMLFiという専用言語もOCamlで作られています。

http://www.lexifi.com/
http://www.lexifi.com/downloads/frisch_inria_2008-12-15.pdf

XenServerのツールスタック
有名な仮想化サーバーXenのツール群は13万行にも及ぶOCamlにて作成されています。これらは有償のソフトウェアです。

( 省略 )

Jane Street Capital
ニューヨークに本社がある投資会社で、クォンツリサーチに全面的にOCamlを活用しています。coreという名前のユーティリティライブラリなど多数の高品質なフリーソフトウェアを公開しています。

[参考リンク]

http://www.janestcapital.com/
http://ocaml.janestcapital.com/?q=node/13

Jane Street is a proprietary trading firm that uses OCaml as its primary development platform. Our operation runs at a large scale, generating billions of dollars of transactions every day from our offices in Hong Kong, London and New York, with strategies that span many asset classes, time-zones and regulatory regimes.

Almost all of of our software is written in OCaml, from statistical research code to systems-administration tools to our real-time trading infrastructure. OCaml’s type system acts as a rich and well-integrated set of static analysis tools that help improve the quality of our code, catching bugs at the earliest possible stage. Billions of dollars of transactions flow through our systems every day, so getting it right matters. At the same time, OCaml is highly productive, helping us quickly adapt to changing market conditions.

Jane Street has been contributing open-source libraries back to the wider community for many years, including Core, our alternative standard library, Async, a cooperative concurrency library, and several syntax extensions like binprot and sexplib. All of these can be found at http://janestreet.github.io. All in, we've open-sourced more than 200k lines of code.

定理証明言語Coqも、OCamlで実装されているとか。

金融業界の雄、Bloomberg社は、OCaml ==> JavaScriptの翻訳トランスコンパイラをリリース

npm install -g bs-platform
git clone https://github.com/rescript-lang/rescript-project-template
cd rescript-project-template
npm install
npm run build
node src/Demo.bs.js

さらに、OCamlのコードをJavaScriptに変換(トランスパイリング)する「BuckleScript 1.0」が、金融業界の巨人、米Bloomberg社からリリースされています。

金融情報などの提供を行っている米ブルームバーグは、OCamlのコードからJavaScriptのコードを生成するトランスパイラ「BuckleScript 1.0」をオープンソースで公開しました。

BuckleScriptはTypeScriptやBabelJSなどからインスパイヤを得て開発されたと説明されていますが、最大の特徴はTypeScriptなどが独自の構文を備えているのに対し、BuckleScriptは既存の言語であるOCamlを採用しているところです。

Bloombergだけでなく、Facebook社もBuckleScriptの誕生に手を貸したと書いてある。。。

Thanks to the OCaml team, obviously, without such a beautiful yet practical language, this backend would not exist
Thanks to ninja-build, ReScript also comes with a blazing fast build tool on top of it, ninja is a truly well engineered scalable build tool
Thanks to Bloomberg and Facebook. This project began at Bloomberg and was published in 2016; without the support of Bloomberg, it would not have happened. This project's funded by Facebook since July/2017

1973年に、かの数学大国、共和制フランスの数理・制御工学・通信理論野総合研究機構INRIA)で産声をあげたML言語の系譜を引いたプログラミング言語「OCaml」は、BuckleScript 1.0の誕生の実例が示しているように、金融業界という産業界で堅実に使われている。


そんなOCamlをMacbookに入れてみます

( 参考にしたWebページ )

@zenwerkさん 「OCaml の環境構築」
@oshuyaさん 「OCamlの環境構築[Mac OS X]」
MacでサクッとOCamlの環境構築をする(+複数バージョンの管理対応)

まずは、(Python)Pyenv / CondaのOCaml版 OPpamのインストールから

Terminal
ocean@AfoGuardMacBook-Pro ~ % brew install opam
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core and homebrew/cask).
==> Updated Formulae
Updated 145 formulae.
==> Updated Casks
Updated 11 casks.

==> Downloading https://homebrew.bintray.com/bottles/gpatch-2.7.6.catalina.bottle.tar.gz
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/opam-2.0.7.catalina.bottle.1.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/2b1115dfcdfe71a806d07da60597a76f0e531c828e33e2c2c9901b0ef343c285?response-content-dispositio
######################################################################## 100.0%
==> Installing dependencies for opam: gpatch
==> Installing opam dependency: gpatch
==> Pouring gpatch-2.7.6.catalina.bottle.tar.gz
🍺  /usr/local/Cellar/gpatch/2.7.6: 10 files, 330.0KB
==> Installing opam
==> Pouring opam-2.0.7.catalina.bottle.1.tar.gz
==> Caveats
OPAM uses ~/.opam by default for its package database, so you need to
initialize it first by running:

$
Terminal
$ opam init

zsh completions have been installed to:
  /usr/local/share/zsh/site-functions
==> Summary
🍺  /usr/local/Cellar/opam/2.0.7: 48 files, 11MB
==> Caveats
==> opam
OPAM uses ~/.opam by default for its package database, so you need to
initialize it first by running:

$

誤ってもう1度、opam initしてしまった。

Terminal
$ opam init

zsh completions have been installed to:
  /usr/local/share/zsh/site-functions
ocean@AfoGuardMacBook-Pro ~ % 
ocean@AfoGuardMacBook-Pro ~ % opam init
[NOTE] Will configure from built-in defaults.
Checking for available remotes: rsync and local, git.
  - you won't be able to use mercurial repositories unless you install the hg command on your system.
  - you won't be able to use darcs repositories unless you install the darcs command on your system.


<><> Fetching repository information ><><><><><><><><><><><><><><><><><><><>  🐫 
[default] Initialised

<><> Required setup - please read <><><><><><><><><><><><><><><><><><><><><>  🐫 

  In normal operation, opam only alters files within ~/.opam.

  However, to best integrate with your system, some environment variables
  should be set. If you allow it to, this initialisation step will update
  your zsh configuration by adding the following line to ~/.zshrc:

    test -r /Users/ocean/.opam/opam-init/init.zsh && . /Users/ocean/.opam/opam-init/init.zsh > /dev/null 2> /dev/null || true

  Otherwise, every time you want to access your opam installation, you will
  need to run:

    eval $(opam env)

  You can always re-run this setup with 'opam init' later.

Do you want opam to modify ~/.zshrc? [N/y/f]
(default is 'no', use 'f' to choose a different file) y
A hook can be added to opam's init scripts to ensure that the shell remains in sync with the opam environment when they are loaded. Set that up? [y/N]
y

User configuration:
  Updating ~/.zshrc.

<><> Creating initial switch (ocaml-base-compiler) ><><><><><><><><><><><><>  🐫 
y
y
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><>  🐫 
Processing  6/6: [ocaml-base-compiler.4.11.1: dl]
[ocaml-base-compiler.4.11.1] downloaded from cache at https://opam.ocaml.org/cache

<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><>  🐫 
∗ installed base-bigarray.base
∗ installed base-threads.base
∗ installed base-unix.base
Processing  7/12: [ocaml-base-compiler: make world]
y
Processing  7/12: [ocaml-base-compiler: make world.opt]
∗ installed ocaml-base-compiler.4.11.1
∗ installed ocaml-config.1
∗ installed ocaml.4.11.1
Done.
# Run eval $(opam env) to update the current shell environment
ocean@AfoGuardMacBook-Pro ~ %
Terminal
ocean@AfoGuardMacBook-Pro ~ % echo eval $(opam env) > ~/.bash_profile
ocean@AfoGuardMacBook-Pro ~ % cat ~/.bash_profile
eval OPAM_SWITCH_PREFIX='/Users/ocean/.opam/default'; export OPAM_SWITCH_PREFIX; CAML_LD_LIBRARY_PATH='/Users/ocean/.opam/default/lib/stublibs:Updated by package ocaml'; export CAML_LD_LIBRARY_PATH; OCAML_TOPLEVEL_PATH='/Users/ocean/.opam/default/lib/toplevel'; export OCAML_TOPLEVEL_PATH; PATH='/Users/ocean/.opam/default/bin:/Users/ocean/.pyenv/shims:/Users/ocean/.pyenv/bin:/Users/ocean/.nodebrew/current/bin:/Users/ocean/.nodebrew/current/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Users/ocean/.cargo/bin'; export PATH;
ocean@AfoGuardMacBook-Pro ~ %

どのバージョンのOCamlが、すでにインストール済なのか確認

Terminal
ocean@AfoGuardMacBook-Pro ~ % opam switch
#  switch   compiler                    description
→  default  ocaml-base-compiler.4.11.1  default

[WARNING] The environment is not in sync with the current switch.
          You should run: eval $(opam env)
ocean@AfoGuardMacBook-Pro ~ %

利用可能なOCamlコンパイラのバージョンを一括出力

Terminal
ocean@AfoGuardMacBook-Pro ~ % opam switch list-available compiler
# Listing available compilers from repositories: default
# Name              # Version     # Synopsis
ocaml-base-compiler 3.07          Official 3.07 release
ocaml-base-compiler 3.07+1        Official 3.07+1 release
ocaml-base-compiler 3.07+2        Official 3.07+2 release
ocaml-base-compiler 3.08.0        Official 3.08.0 release
ocaml-base-compiler 3.08.1        Official 3.08.1 release
ocaml-base-compiler 3.08.2        Official 3.08.2 release
ocaml-base-compiler 3.08.3        Official 3.08.3 release
ocaml-base-compiler 3.08.4        Official 3.08.4 release
ocaml-base-compiler 3.09.0        Official 3.09.0 release
ocaml-base-compiler 3.09.1        Official 3.09.1 release
ocaml-base-compiler 3.09.2        Official 3.09.2 release
ocaml-base-compiler 3.09.3        Official 3.09.3 release
ocaml-base-compiler 3.10.0        Official 3.10.0 release
ocaml-base-compiler 3.10.1        Official 3.10.1 release
ocaml-base-compiler 3.10.2        Official 3.10.2 release
ocaml-base-compiler 3.11.0        Official 3.11.0 release
ocaml-base-compiler 3.11.1        Official 3.11.1 release
ocaml-base-compiler 3.11.2        Official 3.11.2 release
ocaml-base-compiler 3.12.0        Official 3.12.0 release
ocaml-base-compiler 3.12.1        Official 3.12.1 release
ocaml-base-compiler 4.00.0        Official 4.00.0 release
ocaml-base-compiler 4.00.1        Official 4.00.1 release
ocaml-base-compiler 4.01.0        Official 4.01.0 release
ocaml-base-compiler 4.02.0        Official 4.02.0 release
ocaml-base-compiler 4.02.1        Official 4.02.1 release
ocaml-base-compiler 4.02.2        Official 4.02.2 release
ocaml-base-compiler 4.02.3        Official 4.02.3 release
ocaml-base-compiler 4.03.0        Official 4.03.0 release
ocaml-base-compiler 4.04.0        Official 4.04.0 release
ocaml-base-compiler 4.04.1        Official 4.04.1 release
ocaml-base-compiler 4.04.2        Official 4.04.2 release
ocaml-base-compiler 4.05.0        Official 4.05.0 release
ocaml-base-compiler 4.06.0        Official 4.06.0 release
ocaml-base-compiler 4.06.1        Official 4.06.1 release
ocaml-base-compiler 4.07.0        Official release 4.07.0
ocaml-base-compiler 4.07.1        Official release 4.07.1
ocaml-base-compiler 4.08.0        Official release 4.08.0
ocaml-base-compiler 4.08.1        Official release 4.08.1
ocaml-base-compiler 4.09.0        Official release 4.09.0
ocaml-base-compiler 4.09.1        Official release 4.09.1
ocaml-base-compiler 4.10.0        Official release 4.10.0
ocaml-base-compiler 4.10.1        Official release 4.10.1
ocaml-base-compiler 4.10.2        Official release 4.10.2
ocaml-base-compiler 4.11.0        Official release 4.11.0
ocaml-base-compiler 4.11.1        Official release 4.11.1
ocaml-base-compiler 4.12.0~alpha1 First alpha release of OCaml 4.12.0
ocaml-base-compiler 4.12.0~alpha2 Second alpha release of OCaml 4.12.0
ocaml-base-compiler 4.12.0~alpha3 Third alpha release of OCaml 4.12.0
ocean@AfoGuardMacBook-Pro ~ %

インストールできる安定版の中で、最新のOCaml 4.11.1を入れる

Terminal
ocean@AfoGuardMacBook-Pro ~ % opam switch create 4.11.1

<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><>  🐫 
[ocaml-base-compiler.4.11.1] found in cache

<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><>  🐫 
∗ installed base-bigarray.base
∗ installed base-threads.base
∗ installed base-unix.base
Processing  7/12: [ocaml-base-compiler: make world.opt]
∗ installed ocaml-base-compiler.4.11.1
∗ installed ocaml-config.1
∗ installed ocaml.4.11.1
Done.
# Run eval $(opam env) to update the current shell environment
ocean@AfoGuardMacBook-Pro ~ %

インストールした最新のOCaml 04.11.1を使うように設定を切り替える

Terminal
ocean@AfoGuardMacBook-Pro ~ % eval $(opam env)
ocean@AfoGuardMacBook-Pro ~ %

使用中のOCamlのバージョンを確認

Terminal
ocean@AfoGuardMacBook-Pro ~ % ocaml --version
The OCaml toplevel, version 4.11.1
ocean@AfoGuardMacBook-Pro ~ %

使用中のopamのバージョンを確認

Terminal
ocean@AfoGuardMacBook-Pro ~ % opam --version
2.0.7
ocean@AfoGuardMacBook-Pro ~ %

ocamlコマンドでOCamlを実行できるか確認

Terminal
ocean@AfoGuardMacBook-Pro ~ % ocaml
        OCaml version 4.11.1

# ^Z
zsh: suspended  ocaml
ocean@AfoGuardMacBook-Pro ~ %
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?