LoginSignup
2
2

More than 5 years have passed since last update.

Mozart2 - Ozでシステム関数のインポート/関数の遅延評価/パターンマッチしてみる

Last updated at Posted at 2015-01-09

Mozart2 - Oz言語 を利用する (OSX,非emacs,CUI)の続き。
ozcを利用し、コマンドラインでやろうといろいろしてます。

構文に慣れず試行錯誤だけど、要領は分かってきたのでメモ。

$ cat fact2.oz
functor _
require
  % 複数の関数をインポートする際は空白区切りみたい
  System(show:Show showInfo:ShowInfo)
  Application(exit:Exit)
prepare
  % なんでも lazy にしてみる
  fun lazy {Add X Y}
    X + Y
  end

  % case はパターンマッチを行う
  % リストは連結リストなので、パターンマッチで最初の要素と後続の要素に分けられる。最後はnil。
  fun lazy {Sum L}
    case L of H|T then
      {Add H {Sum T}}
    else 0 end
  end

  % いつもの再帰も lazy に
  fun lazy {Fact N}
    if N == 0 then 1
    else N * {Fact N -1 }
    end
  end

  % 遅延評価関数の実行結果は普通に変数に束縛できる
  F = {Fact {Sum [1 2 3 4]}}

  {Show '遅延評価関数の評価前'}
  {Show F}
  {Show '遅延評価関数の評価後'}
  {ShowInfo F}

  {Exit 1}
end

実行してみる。

$ ozc fact2.oz
'遅延評価関数の評価前'
_
'遅延評価関数の評価後'
3628800

$ echo $?
1
  • require のところではモジュールの関数をそれぞれ任意の名前でインポートできる。
  • System#show は評価を行わない(lazy指定された関数の評価実行を引き起こさない)。それに対し、System#showInfo は評価を実行する。
  • System#show とか Systen#print はリストの構造をそのまま出力してくれる。System#showInfoは文字列類似のものしか処理できない。

おまけ

System モジュールの関数などを確認したい場合、github の mozart2 プロジェクトの中に一通りあります。

$ git clone https://github.com/mozart/mozart2
$ cd mozart2
$ cat lib/main/sys/System.oz

... 略 ...
export
   Print
   Show
   PrintName
   PrintInfo
   ShowInfo
   PrintError
   ShowError
   gcDo: GCDo
   Postmortem
   Eq
   % NbSusps
   OnToplevel

define

   proc {Print Value}
      {Boot_System.printRepr Value false false}
   end

... 略 ...
2
2
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
2
2