読者です 読者をやめる 読者になる 読者になる

はわわーっ

はわわわわっ

再帰とかパターンマッチとか

haskell

haskellのお勉強。再帰とか使って関数を作ってみるよ。中身は標準にあるやつとだいたい同じだと思うよ。

maximum' :: (Ord a) => [a] -> a
maximum' [] = error "empty"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)

replicate' :: Int -> a -> [a]
replicate' n x
    | n <= 0 = []
    | otherwise = x : replicate' (n-1) x

take' :: Int -> [a] -> [a]
take' n _
    | n <= 0 = []
take' _ [] = []
take' n (x:xs) = x : take' (n-1) xs

repeat' :: a -> [a]
repeat' x = x : repeat' x

zip' :: [a] -> [b] -> [(a,b)]
zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys

main = do
    print $ maximum' [1,5,3,4,6,2,6,2,7]
    -- 7
    print $ replicate' 3 6
    -- [6,6,6]
    print $ take' 3 [1,5,3,4,6,2,6,2,7]
    -- [1,5,3]
    print $ take' 3 (repeat' 4)
    -- [4,4,4]
    print $ zip' [1..] "abcdef"
    -- [(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),(6,'f')]