2013年2月16日土曜日

開発環境

Real World Haskell』(Bryan O'SullivanJohn GoerzenDon Stewart(著)、山下 伸夫伊東 勝利株式会社タイムインターメディア(翻訳)、オライリー・ジャパン、2009年、ISBN978-4-87311-423-3)の4章(関数プログラミング)の4.6(ループをどのように考えるか)の練習問題1.を解いてみる。

1.

コード(BBEdit)

Sample.hs

asInt_fold :: String -> Int
asInt_fold [] = error("整数が与えられてない")
asInt_fold (x:xs) | x /= '-' = step 0 (x:xs)
                  | xs == [] = error ("マイナス(-)符号しかない")
                  | otherwise = (-1) * (step 0 xs)
                      where step n (x:xs) = let n' = 10 * n + digitToInt x
                                            in step n' xs
                            step n [] = n

入出力結果(Terminal)

$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> asInt_fold "101"
101
*Main> asInt_fold "-31337"
-31337
*Main> asInt_fold "1798"
1798
*Main> :quit
Leaving GHCi.
$

0 コメント:

コメントを投稿