Safe Haskell | Safe |
---|---|
Language | Haskell2010 |
第2章 練習問題 E
- first :: (a -> Bool) -> [a] -> a
- first' :: (b -> Bool) -> (a -> b) -> [a] -> b
- betterFirstB :: (a -> Bool) -> [a] -> Maybe a
- betterFirstS :: (a -> Bool) -> [a] -> Maybe a
- nums :: [Int]
- nums' :: [Int]
- isSquare :: Int -> Bool
- poly :: Int -> Maybe a -> Maybe a
- prna :: Show a => a -> IO String
- prn :: Show a => Maybe a -> IO ()
- samples :: [Maybe ()]
- test :: IO ()
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
isSquare :: Int -> Bool Source #
お試し用述語
isSquare :: Int -> Bool isSquare = (==) * (^2) . round . sqrt . fromIntegral
表示テスト
>>>
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 ⊥