Skip to content

Instantly share code, notes, and snippets.

@akiomik
Last active January 1, 2016 09:29
Show Gist options
  • Save akiomik/8125119 to your computer and use it in GitHub Desktop.
Save akiomik/8125119 to your computer and use it in GitHub Desktop.
すごいH本第4章の再帰をscalaで書く
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
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
}
@akiomik
Copy link
Author

akiomik commented Dec 25, 2013

haskell綺麗過ぎ。まだ省略できるとはいえ、scalaはシグネチャがごつごつする。

遅延リストが残念すぎる。
http://d.hatena.ne.jp/akihiro4chawon/20110505/1304570290

elemは型クラス使ってないので書き直す(いつか)

++ List(x):+ xは変わらない?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment