SSブログ

cut_first_word の書き直し (ExtLib の ExtString.String.implode を使う) [OCaml]

前回の cut_first_word は再帰的な関数で文字列を組み上げるときにString.make して String.concat して、というのが嫌だったので、できればその代わりにリストを使いたい。

でも OCaml の標準ライブラリにはリストを文字列に変換する機能が用意されていないっぽいので、その機能 (implode 関数) がある ExtLib の ExtString というモジュールを入れた。するとこう書ける。

open ExtString.String;;

let stdinstr = Stream.of_channel stdin;;

let words str = 
  let is_space c = String.contains " \t\r\n" c in
  let rec trim_leading charstr =
    match (Stream.peek charstr) with
      Some c -> 
        if is_space c then
          (Stream.junk charstr; trim_leading charstr)
        else
          charstr
    | None -> charstr
  in
  let rec cut_first_word str =
    let c = Stream.next str in
    match (Stream.peek str) with
      Some next_char ->
        if is_space next_char then
          c :: []
        else
          c :: (cut_first_word str)
    | None -> c :: []
  in
  Stream.from (
    fun i -> 
      try
        let trimmed = trim_leading str in
        Some (implode (cut_first_word trimmed))
      with Stream.Failure -> None
  )
;;

Stream.iter (Printf.printf "[%s] ") (words stdinstr);;

それから ExtLib インストールの手順をメモ(extlib-1.5.tar.gz を Windows XP で使用)。

  1. http://ocaml-lib.sourceforge.net/ で入手して適当な場所で ocaml install.ml を実行
  2. 「1- Bytecode installation only」を選択
  3. 「Choose installation directory :」と聞かれるので、「E:\Program Files\Objective Caml\lib\extlib」を作って、「C:\PROGRA~1\OBJECT~1\lib\extlib」を入力(スペース込みだと上手く行かない)
  4. 「Do you want to generate ocamldoc documentation (Y/N) ?」は「N」を入れる(「Y」だと途中のスタイルシートをコピーするらしいところで止まる。面倒なので深追いしない)
  5. OCaml を実行するときは ocaml -I +extlib extlib.cma words.ml と叩く

nice!(0)  コメント(0)  トラックバック(0) 
共通テーマ:パソコン・インターネット

nice! 0

コメント 0

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

トラックバック 0

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。