2013年12月24日火曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-20.をHaskellで解いてみる。

その他参考書籍

12.7(練習問題)、12-20.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import Data.List

main :: IO ()
main = mapM_ print $ map (\(a, b, c, d) -> findButNotAfter a b c == d)
                         testCases

findButNotAfter :: String -> String -> String -> Maybe Int
findButNotAfter src pre pattern = findButNotAfter' src pre pattern 0

findButNotAfter' :: String -> String -> String -> Int -> Maybe Int
findButNotAfter' _ [] [] _ = Nothing
findButNotAfter' _ [] _ _ = Nothing
findButNotAfter' _ _ [] _ = Nothing
findButNotAfter' [] _ _ _ = Nothing
findButNotAfter' src pre pattern n =
    let i = findStr src pattern 0
    in if i == -1 then
           Nothing
       else
           let s = take i src
           in if s == pre then
                  let l = n + i + i
                  in findButNotAfter' (drop l src) pre pattern l
              else
                  Just (n + i)

findStr :: String -> String -> Int -> Int
findStr [] _ _ = -1
findStr src@(_:xs) pattern n = if isPrefixOf pattern src then
                                   n
                               else
                                   findStr xs pattern (n + 1)

testCases :: [(String, String, String, Maybe Int)]
testCases = [("", "", "", Nothing), ("", "", "a", Nothing),
             ("", "a", "", Nothing), ("", "a", "b", Nothing),
             ("a", "", "b", Nothing), ("a", "a", "", Nothing),
             ("abcd", "a", "bc", Nothing), ("abcdcd", "ab", "cd", Just 4),
             ("abxcdcd", "ab", "cd", Just 3)]

入出力結果(Terminal, runghc)

$ runghc Sample.hs
True
True
True
True
True
True
True
True
True
$

慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿