parseした結果をつかわなければ評価されないということの確認。

Parserへの入力文字列が先頭から順番にparseされていくという依存関係によって各Parserが呼び出されていくが、結果を返すreturn xxxはその値が必要とされるまでは遅延評価があるため本当に必要になるまで実行されない。

% cat -n foo.lhs
     1  > import Parsing
     2  > import Debug.Trace
     3
     4  > myread :: Read a => String -> a
     5  > myread xs | trace("{myread " ++ xs ++ "}") False = read xs
     6  > myread xs = read xs
     7
     8  > myint :: Parser Int
     9  > myint =  do xs <- many1 digit
    10  >             return (myread xs)
    11
    12  > myadd :: Parser Int
    13  > myadd =  do a <- myint
    14  >             space
    15  >             b <- myint
    16  >             return (a + b)
    17
    18  > my1st :: Parser Int
    19  > my1st =  do a <- myint
    20  >             space
    21  >             myint
    22  >             return a
% ghci foo.lhs
GHCi, version 7.0.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
[1 of 2] Compiling Parsing          ( Parsing.lhs, interpreted )
[2 of 2] Compiling Main             ( foo.lhs, interpreted )
Ok, modules loaded: Parsing, Main.
*Main> parse myadd "1 2"
Loading package array-0.3.0.2 ... linking ... done.
Loading package filepath-1.2.0.0 ... linking ... done.
Loading package old-locale-1.0.0.2 ... linking ... done.
Loading package old-time-1.0.0.6 ... linking ... done.
Loading package unix-2.4.2.0 ... linking ... done.
Loading package directory-1.1.0.0 ... linking ... done.
Loading package process-1.0.1.5 ... linking ... done.
Loading package time-1.2.0.3 ... linking ... done.
Loading package random-1.0.0.3 ... linking ... done.
Loading package haskell98-1.1.0.1 ... linking ... done.
[({myread 1}
{myread 2}
3,"")]
*Main> parse my1st "1 2"
[({myread 1}
1,"")]
*Main> :quit
Leaving GHCi.
%