関数型プログラミングの基礎 - リスト - 一般的な関数(take, drop, elem)
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT1(関数型プログラミングの基礎)、LESSON 6(リスト)、6.3(練習問題)、Q6-1、Q6-2、Q6-3の解答を求めてみる。
コード
sample.hs
main :: IO ()
main = do
print $ take 10 (repeat 5)
print $ take 10 (myRepeat 5)
print $ subseq 2 5 [1 .. 10]
print $ subseq 2 7 "a puppy"
print $ subseq1 2 5 [1 .. 10]
print $ subseq1 2 7 "a puppy"
print $ inFirstHalf 5 [1 .. 10]
print $ inFirstHalf 6 [1 .. 10]
print $ inFirstHalf 5 [1 .. 9]
print $ inFirstHalf1 5 [1 .. 10]
print $ inFirstHalf1 6 [1 .. 10]
print $ inFirstHalf1 5 [1 .. 9]
-- Q6-1
myRepeat :: a -> [a]
myRepeat x = cycle [x]
-- Q6-2
subseq :: Int -> Int -> [a] -> [a]
subseq start end aList = take (end - start) (drop start aList)
subseq1 :: (Eq t, Num t) => t -> Int -> [a] -> [a]
subseq1 start end aList = if start == 0
then take end aList
else subseq1 (start - 1) (end - 1) (tail aList)
-- Q6-3
inFirstHalf :: Eq a => a -> [a] -> Bool
inFirstHalf x aList = elem x (take (div (length aList) 2) aList)
inFirstHalf1 :: Eq a => a -> [a] -> Bool
inFirstHalf1 x aList = x `elem` take (div (length aList) 2) aList
入出力結果(Terminal, Zsh)
% runghc sample.hs
[5,5,5,5,5,5,5,5,5,5]
[5,5,5,5,5,5,5,5,5,5]
[3,4,5]
"puppy"
[3,4,5]
"puppy"
True
False
False
True
False
False
%