Last active
January 1, 2016 09:29
-
-
Save akiomik/8125119 to your computer and use it in GitHub Desktop.
すごいH本第4章の再帰をscalaで書く
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
reverse' :: [a] -> [a] | |
reverse' [] = [] | |
reverse' (x : xs) = reverse' xs ++ [x] | |
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 | |
elem' :: (Eq a) => a -> [a] -> Bool | |
elem' a [] = False | |
elem' a (x : xs) | |
| a == x = True | |
| otherwise = a `elem'` xs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def replicate[A](n: Int)(x: A): List[A] = n match { | |
case n if n > 0 => x :: replicate(n - 1)(x) | |
case _ => List() | |
} | |
def take[A](n: Int)(x: List[A]): List[A] = x match { | |
case (x :: xs) if n > 0 => x :: take(n - 1)(xs) | |
case _ => List() | |
} | |
def reverse[A](x: List[A]): List[A] = x match { | |
case (x :: xs) => reverse(xs) ++ List(x) | |
case _ => List() | |
} | |
def repeat[A](x: A): List[A] = Stream.continually(x).toList | |
def zip[A, B](x: List[A])(y: List[B]): List[(A, B)] = (x, y) match { | |
case ((x :: xs), (y :: ys)) => (x, y) :: zip(xs)(ys) | |
case _ => List() | |
} | |
def elem[A](a: A)(xs: List[A]): Boolean = xs match { | |
case (x :: xs) if a == x => true | |
case (x :: xs) => elem(a)(xs) | |
case _ => false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
haskell綺麗過ぎ。まだ省略できるとはいえ、scalaはシグネチャがごつごつする。
遅延リストが残念すぎる。
http://d.hatena.ne.jp/akihiro4chawon/20110505/1304570290
elemは型クラス使ってないので書き直す(いつか)
++ List(x)
と:+ x
は変わらない?