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 (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の8章(効率的なファイル処理、正規表現、ファイル名マッチング)、8.5(グロブパターンを正規表現に翻訳する)の練習問題 2.を解いてみる。
その他参考書籍
- すごいHaskellたのしく学ぼう!(オーム社) Miran Lipovača(著)、田中 英行、村主 崇行(翻訳)
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
練習問題 2.
コード(BBEdit, Emacs)
GlobRegex.hs
{-# OPTIONS -Wall -Werror *-} module GlobRegex where import Data.Char import Text.Regex.Posix ((=~)) globToRegex :: String -> Bool -> String globToRegex cs b | b = '^':(map toUpper $ globToRegex' cs) ++ "$" | otherwise = '^':globToRegex' cs ++ "$" globToRegex' :: String -> String globToRegex' "" = "" globToRegex' ('[':'!':c:cs) = undefined globToRegex' ('p':c:cs) = undefined globToRegex' ('[':_) = error "unterminated character class" globToRegex' (c:cs) = escape c ++ globToRegex' cs escape :: Char -> String escape c | c `elem` regexChars = undefined | otherwise = [c] where regexChars = "\\+()^$.{}]|" matchesGlob :: FilePath -> String -> Bool -> Bool matchesGlob name pat b | b = (map toUpper $ name) =~ globToRegex pat b | otherwise = name =~ globToRegex pat b
入出力結果(Terminal, インタプリタghci)
$ cabal install regex-posix-0.95.2 … $ 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 GlobRegex.hs [1 of 1] Compiling GlobRegex ( GlobRegex.hs, interpreted ) Ok, modules loaded: GlobRegex. *GlobRegex> globToRegex "Haskell" True Loading package array-0.4.0.1 ... linking ... done. Loading package deepseq-1.3.0.1 ... linking ... done. Loading package bytestring-0.10.0.2 ... linking ... done. Loading package containers-0.5.0.0 ... linking ... done. Loading package transformers-0.3.0.0 ... linking ... done. Loading package mtl-2.1.2 ... linking ... done. Loading package regex-base-0.93.2 ... linking ... done. Loading package regex-posix-0.95.2 ... linking ... done. "^HASKELL$" *GlobRegex> globToRegex "Haskell" False "^Haskell$" *GlobRegex> matchesGlob "Haskell" "haskell" True True *GlobRegex> matchesGlob "Haskell" "haskell" False False *GlobRegex> :quit Leaving GHCi. $
0 コメント:
コメントを投稿