Beautiful Code

ビューティフルコード (THEORY/IN/PRACTICE)

ビューティフルコード (THEORY/IN/PRACTICE)

第1章Kernighanさん紹介の正規表現コードをHaskellに移植してみました。

import List
import System

main = do
    (regexp:text:_) <- getArgs
    print $ match regexp text

match :: String -> String -> Bool
match [] _ = True
match ('^':cs) text = matchhere cs text
match regexp text = foldl1 (||) $ map (matchhere regexp) (tails text)

matchhere :: String -> String -> Bool
matchhere [] _ = True
matchhere "$" [] = True
matchhere _ [] = False
matchhere (r0:'*':rs) text = matchstar r0 rs text
matchhere (r:rs) (c:cs)
 | matchchar r c = matchhere rs cs
 | otherwise = False

matchstar :: Char -> String -> String -> Bool
matchstar r regexp [] = False
matchstar r regexp text@(c:cs) =  (matchchar r c && matchstar r regexp cs) || matchhere regexp text

matchchar :: Char -> Char -> Bool
matchchar '.' _ = True
matchchar r c = c == r

まつもとゆきひろさんの「コンピュータサイエンスをなめるな」の一言が印象的。確かに一度もまともにコンピュータサイエンスを勉強したことがない。本棚に飾ってある"The Art of Computer Programming"に挑戦しようかな。