2014年1月25日土曜日

開発環境

Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の4章(関数プログラミング)、4.5(リストを使う)、練習問題 2.を解いてみる。

その他参考書籍

練習問題 2.

コード(BBEdit, Emacs)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
module Main where

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith f xs = iter f xs [] []

iter :: (a -> Bool) -> [a] -> [a] -> [[a]] -> [[a]]
iter _ [] [] xss = xss
iter _ [] ys xss = xss ++ [ys]
iter f (x:xs) [] xss = if f x then iter f xs [x] xss else iter f xs [] xss
iter f (x:xs) ys xss = if f x
                       then iter f xs (ys ++ [x]) xss
                       else iter f xs [] (xss ++ [ys])

入出力結果(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 Sample.hs 
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> splitWith even [1, 2, 4]
[[2,4]]
*Main> splitWith even [1, 2, 4, 5]
[[2,4]]
*Main> splitWith even [2, 4, 1, 3]
[[2,4]]
*Main> splitWith even [1, 3, 2, 4, 5, 7]
[[2,4]]
*Main> splitWith even [2, 4, 1, 3, 6, 8]
[[2,4],[6,8]]
*Main> splitWith even [1]
[]
*Main> splitWith even [2]
[[2]]
*Main> splitWith even []
[]
*Main> :quit 
Leaving GHCi.
$

0 コメント:

コメントを投稿