Drkcore

30 09 2010 Haskell RWH Tweet

Real World Haskell 4章 練習問題4-5

takeWhileの実装

まずは再帰で

mytakeWhile :: (a  -> Bool) -> [a] -> [a]
mytakeWhile f [] = []
mytakeWhile f (x:xs) = case f x of
                       True   -> x : mytakeWhile f xs
                       False  -> [] 

続いてfoldrを使って

mytakeWhile' :: (a  -> Bool) -> [a] -> [a]
mytakeWhile' f xs = foldr step [] xs
    where step x ys | f x    = x : ys
                    | otherwise = []


-- *Main> mytakeWhile' (<3) [1,2,3,4,5,4,3,2,1]
-- [1,2]

最初書いてたときにコレって

1:2:3:[]:[]:3:2:1:[]

ってなるよなとか思ったんだけどfoldrの定義見て

-- foldr            :: (a -> b -> b) -> b -> [a] -> b
-- -- foldr _ z []     =  z
-- -- foldr f z (x:xs) =  f x (foldr f z xs)

再帰になってるから[]が返った時点で終了すんのねと。

ProductName Real World Haskell―実戦で学ぶ関数型言語プログラミング
Bryan O'Sullivan,John Goerzen,Don Stewart
オライリージャパン / ¥ 3,990 ()
在庫あり。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021