Real World Haskell
実戦で学ぶ関数型言語プログラミング
(オライリージャパン)
Bryan O'Sullivan (著) John Goerzen (著)
Don Stewart (著)
山下 伸夫 (翻訳) 伊東 勝利 (翻訳)
株式会社タイムインターメディア (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
- The Haskell Platform (インストール方法、モジュール等)
Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の5章(ライブラリを書く: JSONデータの操作)、5.13(プリティプリンタライブラリに肉付けする)、5.13.3(プリティプリンタを追いかける)、練習問題 1.を解いてみる。
その他参考書籍
- すごいHaskellたのしく学ぼう!(オーム社) Miran Lipovača(著)、田中 英行、村主 崇行(翻訳)
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
練習問題 1.
コード(BBEdit, Emacs)
exercises.hs
{-# OPTIONS -Wall -Werror #-} module Prettify where data Doc = Empty | Char Char | Text String | Line | Concat Doc Doc | Union Doc Doc deriving (Show, Eq) -- … -- 5.13.3 練習問題 1 fill :: Int -> Doc -> Doc fill w x = inner 0 [x] where inner :: Int -> [Doc] -> Doc inner col [] = let ws = w - col in if ws > 0 then Text (replicate ws ' ') else Empty inner col (d:ds) = let ws = w - col in case d of Empty -> if ws > 0 then Text (replicate ws ' ') else Empty Char c -> Concat (Char c) (inner (col + 1) ds) Text s -> Concat (Text s) (inner (col + length s) ds) Line -> if ws > 0 then Concat (Concat (Text (replicate ws ' ')) Line) (inner 0 ds) else Concat Line (inner 0 ds) Concat a b -> inner col (a:b:ds) Union a b -> Union (inner col (a:ds)) (inner col (b:ds))
入出力結果(Terminal, インタプリタghci)
$ ghci GHCi, version 7.6.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. Prelude> :load Prettify.hs [1 of 1] Compiling Prettify ( Prettify.hs, interpreted ) Ok, modules loaded: Prettify. *Prettify> fill 0 Empty Empty *Prettify> fill 10 Empty Text " " *Prettify> fill 0 (Char 'a') Concat (Char 'a') Empty *Prettify> fill 10 (Char 'a') Concat (Char 'a') (Text " ") *Prettify> fill 0 (Text "haskell") Concat (Text "haskell") Empty *Prettify> fill 10 (Text "haskell") Concat (Text "haskell") (Text " ") *Prettify> fill 0 Line Concat Line Empty *Prettify> fill 10 Line Concat (Concat (Text " ") Line) (Text " ") *Prettify> fill 0 (Concat (Char 'a') (Text "haskell")) Concat (Char 'a') (Concat (Text "haskell") Empty) *Prettify> fill 10 (Concat (Char 'a') (Text "haskell")) Concat (Char 'a') (Concat (Text "haskell") (Text " ")) *Prettify> :quit Leaving GHCi. $
0 コメント:
コメントを投稿