tfwh-0.3.7.0

Safe HaskellSafe
LanguageHaskell2010

TFwH.Chap02.ExE

Description

第2章 練習問題 E

Synopsis

Documentation

 

first :: (a -> Bool) -> [a] -> a Source #

first :: (a -> Bool) -> [a] -> a
first p = head . filter p
first :: (a -> Bool) -> [a] -> a
first p xs | null xs   = error "Empty list"
           | p x       = x
           | otherwise = firstB p (tail xs)
           where
             x = head xs
>>> let firstS p = head . filter p  -- Susan版
>>> first isSquare nums == firstS isSquare nums
True

first' :: (b -> Bool) -> (a -> b) -> [a] -> b Source #

Susan の first' :: (b -> Bool) -> (a -> b) -> [a] -> b

first' :: (b -> Bool) -> (a -> b) -> [a] -> b
first' p f = head . filter p . map f

Beaver の first'

first'  :: (b -> Bool) -> (a -> b) -> [a] -> b
first' p f xs | null xs = error "Empty list"
              | p x     = x
              | otherwise = first' p f (tail xs)
              where
                x = f (head xs)
>>> let first'S p f = head . filter p . map f
>>> first' isSquare (subtract 1 . (2*)) nums == first'S isSquare (subtract 1 . (2*)) nums
True

betterFirstB :: (a -> Bool) -> [a] -> Maybe a Source #

より好ましい betterFistB (Beaver 版)

betterFirstB :: (a -> Bool) -> [a] -> Maybe a
betterFirstB p xs
  | null xs   = Nothing
  | p x       = Just x
  | otherwise = betterFirstBeaver p (tail xs)
  where
    x = head xs

betterFirstS :: (a -> Bool) -> [a] -> Maybe a Source #

より好ましい betterFistS (Susan 版)

betterFirstS :: (a -> Bool) -> [a] -> Maybe a
betterFirstS p = maybe Nothing (Just . fst) . uncons . filter p
>>> sum nums'
499999500000
>>> betterFirstB isSquare nums' == betterFirstS isSquare nums
True

nums :: [Int] Source #

テスト用データ 1

nums :: [Int]
nums =  [999999, 999998 .. 0]

nums' :: [Int] Source #

テスト用データ 2 nums と同値ですが,先頭の要素を取り出した時点で長さ1000000のリストができています.

isSquare :: Int -> Bool Source #

お試し用述語

isSquare :: Int -> Bool
isSquare = (==) * (^2) . round . sqrt . fromIntegral 

poly :: Int -> Maybe a -> Maybe a Source #

多相関数 polyN :: Maybe a -> Maybe a を生成する関数

prna :: Show a => a -> IO String Source #

型クラスShowのインスタンスである型の値を表示 IO ()

prn :: Show a => Maybe a -> IO () Source #

Maybe a の値を表示 IO ()

samples :: [Maybe ()] Source #

テスト用引数

test :: IO () Source #

表示テスト

>>> test
Nothing
Nothing
Nothing
⊥
-----
Nothing
Just ()
Just ⊥
⊥
-----
Nothing
Just ⊥
Just ⊥
⊥
-----
Nothing
⊥
⊥
⊥
-----
Just ⊥
Nothing
Nothing
⊥
-----
Just ⊥
Just ()
Just ⊥
⊥
-----
Just ⊥
Just ⊥
Just ⊥
⊥
-----
Just ⊥
⊥
⊥
⊥
-----
⊥
Nothing
Nothing
⊥
-----
⊥
Just ()
Just ⊥
⊥
-----
⊥
Just ⊥
Just ⊥
⊥
-----
⊥
⊥
⊥
⊥
-----
Nothing
Nothing
Nothing
Nothing
-----
Just ⊥
Just ⊥
Just ⊥
Just ⊥
-----
Just ⊥
Just ()
Just ⊥
Just ⊥