2014年1月31日金曜日

開発環境

Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の4章(関数プログラミング)、4.6(ループをどのように考えるか)、4.6.9(左畳み込み、遅延性、スペースリーク)、練習問題 5.を解いてみる。

その他参考書籍

練習問題 5.

コード(BBEdit, Emacs)

exercises.hs

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

takeWhileWithRecursive :: (a -> Bool) -> [a] -> [a]
takeWhileWithRecursive _ [] = []
takeWhileWithRecursive f (x:xs)
    | f x = x:takeWhileWithRecursive f xs
    | otherwise = []

takeWhileWithFoldr :: (a -> Bool) -> [a] -> [a]
takeWhileWithFoldr f xs = foldr (\x acc -> if f x then x:acc else []) [] xs

入出力結果(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> let a = [1, 3, 2, 4, 5]
*Main> takeWhile odd a
[1,3]
*Main> takeWhileWithRecursive odd a
[1,3]
*Main> takeWhileWithFoldr odd a
[1,3]
*Main> takeWhile even a
[]
*Main> takeWhileWithRecursive even a
[]
*Main> takeWhileWithFoldr even a
[]
*Main> :quit 
Leaving GHCi.
$

0 コメント:

コメントを投稿