U E D R , A S I H C RSS

Haskell Exercises/Wikibook

http://en.wikibooks.org/wiki/Haskell 을 따라가다 보면 나오는 연습문제
----

Recursion

~php
module Recursion where

factorial 0 = 1
factorial n = n * factorial (n-1)

--이름 충돌로 replication 대신에 rep
rep :: a -> Int -> [a]
rep a 0 = []
rep a n = a:rep a (n-1)

--이름 충돌로 !! 대신에 i
i :: [a] -> Int -> a
(i) list 0 = head list
(i) list index = (i) (tail list) (index-1)

--이름 충돌로 zip 대신에 z
z :: [a] -> [b] -> [(a,b)]
--z _ [] = []
--z [] _ = []
z xs [] = []
z [] ys = []
z (x:xs) (y:ys) = (x,y):z xs ys

List

~java
module List where
takeInt     :: Int -> [Int] -> [Int]
takeInt 0 xs = []
takeInt n (x:xs) = x:takeInt (n-1) xs

dropInt     :: Int -> [Int] -> [Int]
dropInt 0 xs = xs
dropInt n (x:xs) = dropInt (n-1) xs

sumInt     :: [Int] -> Int
sumInt [] = 0
sumInt (x:xs) = x + sumInt xs

scanSum     :: [Int] -> [Int]
scanSum [i] = [i]
scanSum (i1:i2:ints) = i1:scanSum (i1+i2:ints)

diffs       :: [Int] -> [Int]
diffs [i] = []
diffs (i1:i2:ints) = sub i2 i1:diffs (i2:ints)
                    where sub a b = a - b

A Miscellany of Types

~php
myand       :: [Bool] -> Bool
myand (b:[]) = b
myand (b:bs) = (&&) b $ and bs

myor        :: [Bool] -> Bool
myor (b:[]) = b
myor (b:bs) = (||) b $ or bs

myand2 bs = foldl (&&) True bs
myor2 bs = foldl (||) False bs

maxium list = foldl1 max list
minimub list = foldr1 min list

More on Functions

~php
lambda1 xs = map (\x -> x*2 + 3) xs
original1 xs = map f xs
                where f x = x * 2 + 3

lambda2 xs = foldr (\x y -> read x + y) 1 xs
original2 xs = let f x y = read x + y
                in foldr f 1 xs
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:22
Processing time 0.0129 sec