├── INDEX ├── clojure ├── P11.clj ├── P02.clj ├── P03.clj ├── P24.clj ├── P05.clj ├── P01.clj ├── P07.clj ├── P09.clj ├── P15.clj ├── P06.clj ├── P12.clj ├── P04.clj ├── P22.clj ├── P08.clj ├── P23.clj ├── P19.clj ├── P21.clj ├── P20.clj ├── P25.clj ├── P13.clj ├── P17.clj ├── P10.clj ├── P16.clj ├── P14.clj └── P18.clj ├── README ├── haskell ├── p11.hs ├── p24.hs ├── p09.hs ├── p07.hs ├── p12.hs ├── p05.hs ├── p25.hs ├── p02.hs ├── p03.hs ├── p19.hs ├── p23.hs ├── p21.hs ├── p01.hs ├── p04.hs ├── p10.hs ├── p20.hs ├── p15.hs ├── p17.hs ├── p06.hs ├── p16.hs ├── p22.hs ├── p13.hs ├── p08.hs ├── p14.hs └── p18.hs ├── scala ├── P09.scala ├── P24.scala ├── P25.scala ├── P15.scala ├── P11.scala ├── P12.scala ├── P07.scala ├── P19.scala ├── P23.scala ├── P03.scala ├── P05.scala ├── P04.scala ├── P20.scala ├── P06.scala ├── P17.scala ├── P02.scala ├── P22.scala ├── P08.scala ├── P21.scala ├── P10.scala ├── P01.scala ├── P14.scala ├── P18.scala ├── P13.scala └── P16.scala ├── java ├── P07.java ├── P06.java ├── P03.java ├── P09.java ├── P12.java ├── P19.java ├── P04.java ├── P15.java ├── P11.java ├── P24.java ├── P22.java ├── P13.java ├── core │ ├── Pair.java │ └── List.java ├── P05.java ├── P08.java ├── P02.java ├── P10.java ├── P14.java ├── P25.java ├── P17.java ├── P01.java ├── P23.java ├── P21.java ├── P16.java ├── P20.java └── P18.java └── LICENSE /INDEX: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pavelfatin/ninety-nine/HEAD/INDEX -------------------------------------------------------------------------------- /clojure/P11.clj: -------------------------------------------------------------------------------- 1 | ; P11 Modified run-length encoding. 2 | 3 | (defn f1 [l] 4 | (defn f [x] (if (= 1 (first x)) (second x) x)) 5 | (map f l)) -------------------------------------------------------------------------------- /clojure/P02.clj: -------------------------------------------------------------------------------- 1 | ; P02 Find the last but one element of a list. 2 | 3 | ; Built-ins 4 | (defn f1 [l] 5 | (last (butlast l))) 6 | 7 | ; Using index 8 | (defn f2 [l] 9 | (nth (reverse l) 1)) -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | My take on Ninety-Nine Problems in Java, Scala, Clojure and Haskell 2 | 3 | Based on the original Prolog problem list by Werner Hett: 4 | https://sites.google.com/site/prologsite/prolog-problems 5 | 6 | Pavel Fatin, http://pavelfatin.com -------------------------------------------------------------------------------- /clojure/P03.clj: -------------------------------------------------------------------------------- 1 | ; P03 Find the Kth element of a list. 2 | 3 | ; Tail recursion 4 | (defn f1 [l, n] 5 | (if (= n 1) 6 | (first l) 7 | (recur (rest l) (dec n)))) 8 | 9 | ; Using index 10 | (defn f2 [l, n] 11 | (nth l (dec n))) -------------------------------------------------------------------------------- /haskell/p11.hs: -------------------------------------------------------------------------------- 1 | -- P11 Modified run-length encoding. 2 | 3 | data Entry a = Value a | Sequence Int a deriving Show 4 | 5 | f1 :: [(Int, a)] -> [Entry a] 6 | f1 = map toEntry 7 | where toEntry (1, x) = Value x 8 | toEntry (n, x) = Sequence n x -------------------------------------------------------------------------------- /clojure/P24.clj: -------------------------------------------------------------------------------- 1 | ; P24 Lotto: Draw N different random numbers from the set 1..M. 2 | 3 | ; The obvious answer is (P23/f1 n (range 1 m)) 4 | ; Let's use "distinct" for a different solution 5 | (defn f1 [n m] 6 | (take n (distinct (repeatedly #(inc (rand-int m)))))) -------------------------------------------------------------------------------- /scala/P09.scala: -------------------------------------------------------------------------------- 1 | // P09 Pack consecutive duplicates of list elements into sublists. 2 | 3 | // Recursion with "span" 4 | def f1[T]: List[T] => List[List[T]] = { 5 | case Nil => Nil 6 | case h :: t => 7 | val (a, b) = t.span(h ==) 8 | (h :: a) :: f1(b) 9 | } -------------------------------------------------------------------------------- /clojure/P05.clj: -------------------------------------------------------------------------------- 1 | ; P05 Reverse a list. 2 | 3 | ; Predefined function 4 | (defn f0 [l] 5 | (reverse l)) 6 | 7 | ; Tail recursion 8 | (defn f1 [l] 9 | (loop [it l, acc '()] 10 | (if (seq it) 11 | (recur (rest it) (cons (first it) acc)) 12 | acc))) -------------------------------------------------------------------------------- /clojure/P01.clj: -------------------------------------------------------------------------------- 1 | ; P01 Find the last element of a list. 2 | 3 | ; Predefined function 4 | (defn f0 [l] 5 | (last l)) 6 | 7 | ; Tail recursion 8 | (defn f1 [l] 9 | (if (next l) 10 | (recur (rest l)) 11 | (first l))) 12 | 13 | ; Folding 14 | (defn f2 [l] 15 | (reduce (fn [_ b] b) l)) -------------------------------------------------------------------------------- /haskell/p24.hs: -------------------------------------------------------------------------------- 1 | -- P24 Lotto: Draw N different random numbers from the set 1..M. 2 | 3 | import System.Random 4 | import Data.List 5 | 6 | -- The obvious answer is P23.f1 n [1..m] 7 | -- Let's use "nub" for a different solution 8 | f1 :: RandomGen g => Int -> Int -> g -> [Int] 9 | f1 n m = take n . nub . randomRs (1, m) -------------------------------------------------------------------------------- /clojure/P07.clj: -------------------------------------------------------------------------------- 1 | ; P07 Flatten a nested list structure. 2 | 3 | ; Predefined functions 4 | (defn f0 [l] 5 | (flatten l)) 6 | 7 | ; Recursion 8 | (defn f1 [l] 9 | (if (seq l) 10 | (let [h (first l) t (rest l)] 11 | (if (list? h) 12 | (concat (f1 h) (f1 t)) 13 | (cons h (f1 t)))) 14 | '())) -------------------------------------------------------------------------------- /haskell/p09.hs: -------------------------------------------------------------------------------- 1 | -- P09 Pack consecutive duplicates of list elements into sublists. 2 | 3 | import Data.List 4 | 5 | -- Built-in function 6 | f0 :: Eq a => [a] -> [[a]] 7 | f0 = group 8 | 9 | -- Recursion with "span" 10 | f1 :: Eq a => [a] -> [[a]] 11 | f1 [] = [] 12 | f1 (x:xs) = let (a, b) = span (== x) xs in (x : a) : f1 b -------------------------------------------------------------------------------- /scala/P24.scala: -------------------------------------------------------------------------------- 1 | // P24 Lotto: Draw N different random numbers from the set 1..M. 2 | 3 | import util.Random 4 | 5 | // The obvious answer is P23.f1(n, (1 to m).toList) 6 | // Let's use "distinct" for a different solution 7 | def f1[T](n: Int, m: Int): List[Int] = 8 | Stream.continually(1 + Random.nextInt(m)).distinct.take(n).toList -------------------------------------------------------------------------------- /clojure/P09.clj: -------------------------------------------------------------------------------- 1 | ; P09 Pack consecutive duplicates of list elements into sublists. 2 | 3 | ; Predefined function 4 | (defn f0 [l] 5 | (partition-by identity l)) 6 | 7 | ; Recursion with "split-with" 8 | (defn f1 [l] 9 | (if (seq l) 10 | (let [h (first l) t (rest l) [a b] (split-with #(= % h) t)] 11 | (cons (cons h a) (f1 b))) 12 | '())) -------------------------------------------------------------------------------- /haskell/p07.hs: -------------------------------------------------------------------------------- 1 | -- P07 Flatten a nested list structure. 2 | 3 | data NestedList a = Value a | List [NestedList a] 4 | 5 | -- Recursion 6 | f1 :: NestedList a -> [a] 7 | f1 (Value a) = [a] 8 | f1 (List []) = [] 9 | f1 (List (x:xs)) = (f1 x) ++ f1(List xs) 10 | 11 | -- Using concatMap 12 | f2 :: NestedList a -> [a] 13 | f2 (Value a) = [a] 14 | f2 (List xs) = concatMap f2 xs -------------------------------------------------------------------------------- /scala/P25.scala: -------------------------------------------------------------------------------- 1 | // P25 Generate a random permutation of the elements of a list. 2 | 3 | import util.Random 4 | 5 | // The obvious answer is P23.f1(list.length, list) 6 | // Let's directly select a random permutation for a different implementation 7 | def f1[T](list: List[T]): List[T] = { 8 | val all = list.permutations.toList 9 | all(Random.nextInt(all.length)) 10 | } -------------------------------------------------------------------------------- /clojure/P15.clj: -------------------------------------------------------------------------------- 1 | ; P15 Replicate the elements of a list a given number of times. 2 | 3 | ; Replicate then mapcat 4 | (defn f1 [n l] 5 | (mapcat #(repeat n %) l)) 6 | 7 | ; Without using "repeat", one-pass concatenation 8 | (defn f2 [n l] 9 | (defn prepend [n x xs] 10 | (if (zero? n) xs (cons x (prepend (dec n) x xs)))) 11 | (reduce #(prepend n %2 %1) '() (reverse l))) -------------------------------------------------------------------------------- /clojure/P06.clj: -------------------------------------------------------------------------------- 1 | ; P06 Find out whether a list is a palindrome. 2 | ; A palindrome can be read forward or backward; e.g. (x a m a x). 3 | 4 | ; Tail recursion 5 | (defn f1 [l] 6 | (or (empty? l) 7 | (empty? (rest l)) 8 | (and 9 | (= (first l) (last l)) 10 | (recur (butlast (rest l)))))) 11 | 12 | ; Builtin "reverse" 13 | (defn f2 [l] 14 | (= l (reverse l))) -------------------------------------------------------------------------------- /clojure/P12.clj: -------------------------------------------------------------------------------- 1 | ; P12 Decode a run-length encoded list. 2 | 3 | ; Mapping 4 | (defn f1 [l] 5 | (defn f [x] (if (vector? x) (repeat (first x) (second x)) x)) 6 | (flatten (map f l))) 7 | 8 | ; Recursion 9 | (defn f2 [l] 10 | (if (seq l) 11 | (let [h (first l) t (rest l)] 12 | (if (vector? h) 13 | (concat (repeat (first h) (second h)) (f2 t)) 14 | (cons h (f2 t)))) 15 | '())) -------------------------------------------------------------------------------- /scala/P15.scala: -------------------------------------------------------------------------------- 1 | // P15 Replicate the elements of a list a given number of times. 2 | 3 | // Flat map with replication 4 | def f1[T](n: Int, list: List[T]) = 5 | list.flatMap(List.fill(n)(_)) 6 | 7 | // One-pass concatenation 8 | def f2[T](n: Int, list: List[T]) = 9 | list.foldRight(Nil: List[T])(prepend(n, _, _)) 10 | 11 | def prepend[T](n: Int, x: T, xs: List[T]): List[T] = 12 | if (n == 0) xs else x :: prepend(n - 1, x, xs) -------------------------------------------------------------------------------- /clojure/P04.clj: -------------------------------------------------------------------------------- 1 | ; P04 Find the number of elements of a list. 2 | 3 | ; Predefined function 4 | (defn f0 [l] 5 | (count l)) 6 | 7 | ; Recursion 8 | (defn f1 [l] 9 | (if (seq l) 10 | (inc (f1 (rest l))) 11 | 0)) 12 | 13 | ; Tail recursion 14 | (defn f2 [l] 15 | (loop [it l, n 0] 16 | (if (seq it) 17 | (recur (rest it) (inc n)) 18 | n))) 19 | 20 | ; Folding 21 | (defn f3 [l] 22 | (reduce (fn [a _] (inc a)) 0 l)) -------------------------------------------------------------------------------- /haskell/p12.hs: -------------------------------------------------------------------------------- 1 | -- P12 Decode a run-length encoded list. 2 | 3 | data Entry a = Value a | Sequence Int a deriving Show 4 | 5 | -- Using concatMap 6 | f1 :: [Entry a] -> [a] 7 | f1 = concatMap toItems 8 | where toItems (Value v) = [v] 9 | toItems (Sequence n v) = replicate n v 10 | 11 | -- Recursion 12 | f2 :: [Entry a] -> [a] 13 | f2 [] = [] 14 | f2 ((Value v) : xs) = v : f2 xs 15 | f2 ((Sequence n v) : xs) = replicate n v ++ f2 xs -------------------------------------------------------------------------------- /haskell/p05.hs: -------------------------------------------------------------------------------- 1 | -- P05 Reverse a list. 2 | 3 | -- Predefined function 4 | f0 :: [a] -> [a] 5 | f0 = reverse 6 | 7 | -- Recursion (inefficient) 8 | f1 :: [a] -> [a] 9 | f1 [] = [] 10 | f1 (x:xs) = f1 xs ++ [x] 11 | 12 | -- Tail recursion 13 | f2 :: [a] -> [a] 14 | f2 = f2' [] 15 | where f2' :: [a] -> [a] -> [a] 16 | f2' acc [] = acc 17 | f2' acc (x:xs) = f2' (x:acc) xs 18 | 19 | -- Folding 20 | f3 :: [a] -> [a] 21 | f3 = foldl (flip (:)) [] -------------------------------------------------------------------------------- /java/P07.java: -------------------------------------------------------------------------------- 1 | // P07 Flatten a nested list structure. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P07 { 8 | // Recursion, unchecked 9 | @SuppressWarnings("unchecked") 10 | List f1(List list) { 11 | if (list.isEmpty()) return nil(); 12 | Object h = list.head(); 13 | List t = list.tail(); 14 | return h instanceof List ? concat(f1((List) h), f1(t)) : cons(h, f1(t)); 15 | } 16 | } -------------------------------------------------------------------------------- /haskell/p25.hs: -------------------------------------------------------------------------------- 1 | -- P25 Generate a random permutation of the elements of a list. 2 | 3 | import System.Random 4 | import Data.List 5 | 6 | -- The obvious answer is P23.f1 (length xs) xs 7 | -- Let's directly select a random permutation for a different implementation 8 | f1 :: RandomGen g => [a] -> g -> [a] 9 | f1 g xs = let (i, _) = randomR (0, total - 1) g in permutations xs !! i 10 | where fact n = product [1..n] 11 | total = fact $ length xs -------------------------------------------------------------------------------- /scala/P11.scala: -------------------------------------------------------------------------------- 1 | // P11 Modified run-length encoding. 2 | 3 | // List of objects 4 | def f1[T](list: List[(Int, T)]): List[Any] = list.map { 5 | case (1, x) => x 6 | case it => it 7 | } 8 | 9 | // With custom data 10 | abstract sealed class Entry[T] 11 | case class Value[T](v: T) extends Entry[T] 12 | case class Sequence[T](n: Int, v: T) extends Entry[T] 13 | 14 | def f2[T](list: List[(Int, T)]): List[Entry[T]] = list.map { 15 | case (1, x) => Value(x) 16 | case (n, x) => Sequence(n, x) 17 | } -------------------------------------------------------------------------------- /clojure/P22.clj: -------------------------------------------------------------------------------- 1 | ; P22 Create a list containing all integers within a given range. 2 | 3 | ; Predefined function 4 | (defn f1 [a b] 5 | (range a (inc b))) 6 | 7 | ; As a sum 8 | (defn f2 [a b] 9 | (reductions + a (repeat (- b a) 1))) 10 | 11 | ; Recursion 12 | (defn f3 [a b] 13 | (if (<= a b) 14 | (cons a (f3 (inc a) b)) 15 | '())) 16 | 17 | ; Tail recursion 18 | (defn f4 [a b] 19 | (loop [i a, k b, acc '()] 20 | (if (>= k i) 21 | (recur i (dec k) (cons k acc)) 22 | acc))) -------------------------------------------------------------------------------- /clojure/P08.clj: -------------------------------------------------------------------------------- 1 | ; P08 Eliminate consecutive duplicates of list elements. 2 | 3 | ; Predefined functions 4 | (defn f1 [l] 5 | (map first (partition-by identity l))) 6 | 7 | ; Recursion with "drop-while" 8 | (defn f2 [l] 9 | (if (seq l) 10 | (let [h (first l) t (rest l)] 11 | (cons h (f2 (drop-while #(= % h) t)))) 12 | '())) 13 | 14 | ; Recursion 15 | (defn f3 [l] 16 | (if (next l) 17 | (let [a (first l) b (second l) t (rest l)] 18 | (if (= a b) (f3 t) (cons a (f3 t)))) 19 | l)) -------------------------------------------------------------------------------- /haskell/p02.hs: -------------------------------------------------------------------------------- 1 | -- P02 Find the last but one element of a list. 2 | 3 | -- Recursion 4 | f1 :: [a] -> a 5 | f1 [] = error "empty list" 6 | f1 [_] = error "singleton list" 7 | f1 [x,_] = x 8 | f1 (_:xs) = f1 xs 9 | 10 | -- Function application 11 | f2 :: [a] -> a 12 | f2 xs = last $ init xs 13 | 14 | -- Function composition 15 | f3 :: [a] -> a 16 | f3 = last . init 17 | 18 | -- Folding 19 | f4 :: [a] -> a 20 | f4 = foldr1 (const id) . init 21 | 22 | -- Using index 23 | f5 :: [a] -> a 24 | f5 x = reverse x !! 1 -------------------------------------------------------------------------------- /clojure/P23.clj: -------------------------------------------------------------------------------- 1 | ; P23 Extract a given number of randomly selected elements from a list. 2 | 3 | ; Helper function 4 | (defn remove-at [n l] 5 | (let [[a [x & b]] (split-at n l)] 6 | [(concat a b) x])) 7 | 8 | ; Building a target list while removing items from the source (recursively) 9 | ; Time complexity is O(n^2) in worst and average cases, O(n) - in best case 10 | (defn f1 [n l] 11 | (if (pos? n) 12 | (let [i (rand-int (count l)), [xs x] (remove-at i l)] 13 | (cons x (f1 (dec n) xs))) 14 | '())) -------------------------------------------------------------------------------- /scala/P12.scala: -------------------------------------------------------------------------------- 1 | // P12 Decode a run-length encoded list. 2 | 3 | // List of objects 4 | def f1(list: List[Any]): List[Any] = list.flatMap { 5 | case (n: Int, x) => List.fill(n)(x) 6 | case x => x :: Nil 7 | } 8 | 9 | // With custom data 10 | abstract sealed class Entry[T] 11 | case class Value[T](v: T) extends Entry[T] 12 | case class Sequence[T](n: Int, v: T) extends Entry[T] 13 | 14 | def f2[T](list: List[Entry[T]]): List[T] = list.flatMap { 15 | case Value(v) => v :: Nil 16 | case Sequence(n, v) => List.fill(n)(v) 17 | } -------------------------------------------------------------------------------- /haskell/p03.hs: -------------------------------------------------------------------------------- 1 | -- P03 Find the Kth element of a list. 2 | 3 | -- Tail recursion 4 | f1 :: [a] -> Int -> a 5 | f1 [] _ = error "Index out of bound" 6 | f1 (x:_) 1 = x 7 | f1 (_:xs) n 8 | | n < 1 = error "Index out of bound" 9 | | otherwise = f1 xs (n - 1) 10 | 11 | -- Function application 12 | f2 :: [a] -> Int -> a 13 | f2 xs n = head $ drop (n - 1) xs 14 | 15 | -- Function composition 16 | f3 :: [a] -> Int -> a 17 | f3 xs n = last . take n $ xs 18 | 19 | -- Using index 20 | f4 :: [a] -> Int -> a 21 | f4 xs n = xs !! (n - 1) -------------------------------------------------------------------------------- /haskell/p19.hs: -------------------------------------------------------------------------------- 1 | -- P19 Rotate a list N places to the left. 2 | 3 | -- Using "splitAt" 4 | f1 :: Int -> [a] -> [a] 5 | f1 _ [] = [] 6 | f1 n xs = let (a, b) = splitAt (mod n $ length xs) xs in b ++ a 7 | 8 | -- Without using "let" 9 | f2 :: Int -> [a] -> [a] 10 | f2 _ [] = [] 11 | f2 n xs = uncurry (flip (++)) $ splitAt (mod n $ length xs) xs 12 | 13 | -- Tail recursion 14 | f3 :: Int -> [a] -> [a] 15 | f3 _ [] = [] 16 | f3 0 xs = xs 17 | f3 n xs 18 | | n > 0 = f3 (pred n) (tail xs ++ [head xs]) 19 | | otherwise = f3 (succ n) (last xs : init xs) -------------------------------------------------------------------------------- /scala/P07.scala: -------------------------------------------------------------------------------- 1 | // P07 Flatten a nested list structure. 2 | 3 | // flatMap with recursion, unchecked 4 | def f1(list: List[Any]): List[Any] = list flatMap { 5 | case xs: List[_] => f1(xs) 6 | case v => List(v) 7 | } 8 | 9 | // With custom data 10 | abstract sealed class NestedList[T] 11 | case class Value[T](v: T) extends NestedList[T] 12 | case class Sequence[T](list: List[NestedList[T]]) extends NestedList[T] 13 | 14 | def f2[T]: NestedList[T] => List[T] = { 15 | case Value(v) => List(v) 16 | case Sequence(list) => list.flatMap(f2) 17 | } -------------------------------------------------------------------------------- /java/P06.java: -------------------------------------------------------------------------------- 1 | // P06 Find out whether a list is a palindrome. 2 | // A palindrome can be read forward or backward; e.g. (x a m a x). 3 | 4 | import core.List; 5 | 6 | import static core.List.*; 7 | 8 | class P06 { 9 | // Builtin functions 10 | boolean f1(List list) { 11 | return list.equals(list.reverse()); 12 | } 13 | 14 | // Recursion (inefficient) 15 | boolean f2(List list) { 16 | return list.isEmpty() || list.tail().isEmpty() || 17 | (list.head() == list.last() && f2(list.tail().init())); 18 | } 19 | } -------------------------------------------------------------------------------- /haskell/p23.hs: -------------------------------------------------------------------------------- 1 | -- P23 Extract a given number of randomly selected elements from a list. 2 | 3 | import System.Random 4 | 5 | -- Building a target list while removing items from the source (recursively) 6 | -- Time complexity is O(n^2) in worst and average cases, O(n) - in best case 7 | f1 :: RandomGen g => Int -> [a] -> g -> [a] 8 | f1 0 _ _ = [] 9 | f1 n xs g = let (i, g') = randomR (0, length xs - 1) g 10 | (xs', x) = rm i xs 11 | in x : f1 (pred n) xs' g' 12 | 13 | -- Helper function 14 | rm :: Int -> [a] -> ([a], a) 15 | rm n xs = let (a, x:b) = splitAt n xs in (a ++ b, x) -------------------------------------------------------------------------------- /scala/P19.scala: -------------------------------------------------------------------------------- 1 | // P19 Rotate a list N places to the left. 2 | 3 | // Using "splitAt" 4 | def f1[T](list: List[T], n: Int): List[T] = { 5 | val l = list.size 6 | val i = if (list.nonEmpty) n % l else 0 7 | val (a, b) = list.splitAt(if (i < 0) l + i else i) 8 | b ::: a 9 | } 10 | 11 | // Tail recursion 12 | @annotation.tailrec 13 | def f2[T](list: List[T], n: Int): List[T] = (list, n) match { 14 | case (Nil, _) => Nil 15 | case (xs, 0) => xs 16 | case (xs, n) => 17 | if (n > 0) 18 | f2(xs.tail ::: List(xs.head), n - 1) 19 | else 20 | f2(xs.last :: xs.init, n + 1) 21 | } -------------------------------------------------------------------------------- /clojure/P19.clj: -------------------------------------------------------------------------------- 1 | ; P19 Rotate a list N places to the left. 2 | 3 | ; Using "split-at" 4 | (defn f1 [n l] 5 | (if (seq l) 6 | (let [[a b] (split-at (mod n (count l)) l)] 7 | (concat b a)) 8 | '())) 9 | 10 | ; Without using "let" 11 | (defn f2 [n l] 12 | (if (seq l) 13 | (apply concat 14 | (reverse (split-at (mod n (count l)) l))) 15 | '())) 16 | 17 | ; Tail recursion 18 | (defn f3 [n l] 19 | (if (and (seq l) (not (zero? n))) 20 | (if (pos? n) 21 | (recur (dec n) (concat (rest l) (list (first l)))) 22 | (recur (inc n) (cons (last l) (drop-last l)))) 23 | l)) -------------------------------------------------------------------------------- /haskell/p21.hs: -------------------------------------------------------------------------------- 1 | -- P21 Insert an element at a given position into a list. 2 | 3 | -- Using "splitAt" 4 | f1 :: Int -> a -> [a] -> [a] 5 | f1 n x ys = let (a, b) = splitAt (pred n) ys in a ++ x : b 6 | 7 | -- By index (inefficient) 8 | f2 :: Int -> a -> [a] -> [a] 9 | f2 n x ys = take (pred n) ys ++ x : drop (pred n) ys 10 | 11 | -- Recursion 12 | f3 :: Int -> a -> [a] -> [a] 13 | f3 1 x ys = x : ys 14 | f3 n x (y:ys) = y : f3 (pred n) x ys 15 | 16 | -- Tail recursion 17 | f4 :: Int -> a -> [a] -> [a] 18 | f4 = f [] 19 | where f acc 1 x ys = reverse acc ++ x : ys 20 | f acc n x (y:ys) = f (y:acc) (pred n) x ys -------------------------------------------------------------------------------- /scala/P23.scala: -------------------------------------------------------------------------------- 1 | // P23 Extract a given number of randomly selected elements from a list. 2 | 3 | import util.Random 4 | 5 | // Building a target list while removing items from the source (recursively) 6 | // Time complexity is O(n^2) in worst and average cases, O(n) - in best case 7 | def f1[T](n: Int, list: List[T]): List[T] = { 8 | if (n > 0) { 9 | val (xs, x) = removeAt(list, Random.nextInt(list.size)) 10 | x :: f1(n - 1, xs) 11 | } else { 12 | Nil 13 | } 14 | } 15 | 16 | // Helper function 17 | def removeAt[T](list: List[T], n: Int): (List[T], T) = { 18 | val (a, x :: b) = list.splitAt(n) 19 | (a ::: b, x) 20 | } -------------------------------------------------------------------------------- /clojure/P21.clj: -------------------------------------------------------------------------------- 1 | ; P21 Insert an element at a given position into a list. 2 | 3 | ; Using "split-at" 4 | (defn f1 [n x l] 5 | (let [[a b] (split-at (dec n) l)] 6 | (concat a (cons x b)))) 7 | 8 | ; By index (inefficient) 9 | (defn f2 [n x l] 10 | (concat (take (dec n) l) (cons x (drop (dec n) l)))) 11 | 12 | ; Recursion 13 | (defn f3 [n x l] 14 | (if (= n 1) 15 | (cons x l) 16 | (cons (first l) (f3 (dec n) x (rest l))))) 17 | 18 | ; Tail recursion 19 | (defn f4 [n x l] 20 | (loop [i n ys l acc '()] 21 | (if (= i 1) 22 | (concat (reverse acc) (cons x ys)) 23 | (recur (dec i) (rest ys) (cons (first ys) acc))))) -------------------------------------------------------------------------------- /haskell/p01.hs: -------------------------------------------------------------------------------- 1 | -- P01 Find the last element of a list. 2 | 3 | -- Predefined function 4 | f0 :: [a] -> a 5 | f0 = last 6 | 7 | -- Recursion 8 | f1 :: [a] -> a 9 | f1 [] = error "empty list" 10 | f1 [x] = x 11 | f1 (_:xs) = f1 xs 12 | 13 | -- Function application 14 | f2 :: [a] -> a 15 | f2 xs = head $ reverse xs 16 | 17 | -- Function composition 18 | f3 :: [a] -> a 19 | f3 = head . reverse 20 | 21 | -- Folding 22 | f4 :: [a] -> a 23 | f4 = foldl (curry snd) (error "empty list") 24 | 25 | f5 :: [a] -> a 26 | f5 = foldr1 (flip const) 27 | 28 | f6 :: [a] -> a 29 | f6 = foldr1 (const id) 30 | 31 | f7 :: [a] -> a 32 | f7 = foldr1 (\_ y -> y) -------------------------------------------------------------------------------- /haskell/p04.hs: -------------------------------------------------------------------------------- 1 | -- P04 Find the number of elements of a list. 2 | 3 | -- Predefined function 4 | f0 :: [a] -> Int 5 | f0 = length 6 | 7 | -- Recursion 8 | f1 :: [a] -> Int 9 | f1 [] = 0 10 | f1 (_:xs) = 1 + f1 xs 11 | 12 | -- Tail recursion 13 | f2 :: [a] -> Int 14 | f2 = f2' 0 15 | where f2' :: Int -> [a] -> Int 16 | f2' n [] = n 17 | f2' n (_:xs) = f2' (n + 1) xs 18 | 19 | -- Folding 20 | f3 :: [a] -> Int 21 | f3 = foldl (\a _ -> a + 1) 0 22 | 23 | -- Folding with function composition 24 | f4 :: [a] -> Int 25 | f4 = foldr (const (+1)) 0 26 | 27 | -- Using build-in 'sum' 28 | f5 :: [a] -> Int 29 | f5 = sum . map (const 1) -------------------------------------------------------------------------------- /haskell/p10.hs: -------------------------------------------------------------------------------- 1 | -- P10 Run-length encoding of a list. 2 | 3 | -- Mapping 4 | f1 :: [[a]] -> [(Int, a)] 5 | f1 = map (\x -> (length x, head x)) 6 | 7 | -- Mapping with "zip" 8 | f2 :: [[a]] -> [(Int, a)] 9 | f2 xs = zip (map length xs) (map head xs) 10 | 11 | -- Folding 12 | f3 :: [[a]] -> [(Int, a)] 13 | f3 = foldr (\x acc -> (length x, head x) : acc) [] 14 | 15 | -- Recursion 16 | f4 :: [[a]] -> [(Int, a)] 17 | f4 [] = [] 18 | f4 (x:xs) = (length x, head x) : f4 xs 19 | 20 | -- Tail recursion 21 | f5 :: [[a]] -> [(Int, a)] 22 | f5 = f5' [] 23 | where f5' acc [] = reverse acc 24 | f5' acc (x:xs) = f5' ((length x, head x) : acc) xs -------------------------------------------------------------------------------- /scala/P03.scala: -------------------------------------------------------------------------------- 1 | // P03 Find the Kth element of a list. 2 | 3 | // Tail recursion 4 | @annotation.tailrec 5 | def f1[T](list: List[T], n: Int): T = list match { 6 | case Nil => throw new IndexOutOfBoundsException() 7 | case h :: t => 8 | if (n < 1) throw new IndexOutOfBoundsException() 9 | if (n == 1) h else f1(t, n - 1) 10 | } 11 | 12 | // Calls chain 13 | def f2[T](list: List[T], n: Int): T = list.drop(n - 1).head 14 | 15 | // Using index 16 | def f3[T](list: List[T], n: Int): T = list(n - 1) 17 | 18 | // With error reporting 19 | def f4[T](list: List[T], n: Int): T = list.lift(n - 1).getOrElse(throw new IndexOutOfBoundsException()) -------------------------------------------------------------------------------- /clojure/P20.clj: -------------------------------------------------------------------------------- 1 | ; P20 Remove the K'th element from a list. 2 | 3 | ; Using "split-at" 4 | (defn f1 [n l] 5 | (let [[a [x & b]] (split-at (dec n) l)] 6 | [(concat a b) x])) 7 | 8 | ; By index (inefficient) 9 | (defn f2 [n l] 10 | [(concat (take (dec n) l) (drop n l)) (nth l (dec n))]) 11 | 12 | ; Recursion 13 | (defn f3 [n l] 14 | (let [[h & t] l] 15 | (if (> n 1) 16 | (let [[a b] (f3 (dec n) t)] 17 | [(cons h a) b]) 18 | [t h]))) 19 | 20 | ; Tail recursion 21 | (defn f4 [n l] 22 | (loop [acc '() i n [h & t] l] 23 | (if (> i 1) 24 | (recur (cons h acc) (dec i) t) 25 | [(concat (reverse acc) t) h]))) -------------------------------------------------------------------------------- /java/P03.java: -------------------------------------------------------------------------------- 1 | // P03 Find the Kth element of a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P03 { 8 | // Recursion 9 | T f1(List list, int n) { 10 | if (list.isEmpty()) throw new IndexOutOfBoundsException(); 11 | if (n < 1) throw new IndexOutOfBoundsException(); 12 | return n == 1 ? list.head() : f1(list.tail(), n - 1); 13 | } 14 | 15 | // Calls chain 16 | T f2(List list, int n) { 17 | return list.drop(n - 1).head(); 18 | } 19 | 20 | // Using index 21 | T f3(List list, int n) { 22 | return list.get(n - 1); 23 | } 24 | } -------------------------------------------------------------------------------- /haskell/p20.hs: -------------------------------------------------------------------------------- 1 | -- Remove the K'th element from a list. 2 | 3 | -- Using "splitAt" 4 | f1 :: Int -> [a] -> ([a], a) 5 | f1 n xs = let (a, x:b) = splitAt (pred n) xs in (a ++ b, x) 6 | 7 | -- By index (inefficient) 8 | f2 :: Int -> [a] -> ([a], a) 9 | f2 n xs = (take (pred n) xs ++ drop n xs, xs !! (pred n)) 10 | 11 | -- Recursion 12 | f3 :: Int -> [a] -> ([a], a) 13 | f3 n (x:xs) 14 | | n > 1 = let (a, b) = f3 (pred n) xs in (x : a, b) 15 | | otherwise = (xs, x) 16 | 17 | -- Tail recursion 18 | f4 :: Int -> [a] -> ([a], a) 19 | f4 = f [] 20 | where f acc n (x:xs) 21 | | n > 1 = f (x : acc) (pred n) xs 22 | | otherwise = (reverse acc ++ xs, x) -------------------------------------------------------------------------------- /clojure/P25.clj: -------------------------------------------------------------------------------- 1 | ; P25 Generate a random permutation of the elements of a list. 2 | 3 | ; Helper function 4 | (defn remove-at [n l] 5 | (let [[a [x & b]] (split-at n l)] 6 | [(concat a b) x])) 7 | 8 | ; Generates all permutations 9 | (defn permutations [l] 10 | (if (seq l) 11 | (mapcat 12 | (fn [n] 13 | (let [[xs x] (remove-at n l)] 14 | (map #(cons x %) (permutations xs)))) 15 | (range (count l))) 16 | '(()))) 17 | 18 | ; The obvious answer is (P23/f1 (length l) l) 19 | ; Let's directly select a random permutation for a different implementation 20 | (defn f1 [l] 21 | (let [all (permutations l)] 22 | (nth all (rand-int (count l))))) -------------------------------------------------------------------------------- /haskell/p15.hs: -------------------------------------------------------------------------------- 1 | -- P15 Replicate the elements of a list a given number of times. 2 | 3 | -- Using concatMap and replicate 4 | f1 :: Int -> [a] -> [a] 5 | f1 n xs = concatMap (replicate n) xs 6 | 7 | -- With function composition 8 | f2 :: Int -> [a] -> [a] 9 | f2 = concatMap . replicate 10 | 11 | -- Without "replicate" (folding with concatenation) 12 | f3 :: Int -> [a] -> [a] 13 | f3 n = foldr ((++).(rep n)) [] 14 | where rep 0 _ = [] 15 | rep n x = x : rep (pred n) x 16 | 17 | -- More efficient version (one-pass concatenation) 18 | f4 :: Int -> [a] -> [a] 19 | f4 n = foldr (prepend n) [] 20 | where prepend 0 _ xs = xs 21 | prepend n x xs = x : prepend (pred n) x xs -------------------------------------------------------------------------------- /haskell/p17.hs: -------------------------------------------------------------------------------- 1 | -- P17 Split a list into two parts; the length of the first part is given. 2 | 3 | -- Using predefined function 4 | f1 :: Int -> [a] -> ([a], [a]) 5 | f1 = splitAt 6 | 7 | -- Using "take" and "drop" 8 | f2 :: Int -> [a] -> ([a], [a]) 9 | f2 n xs = (take n xs, drop n xs) 10 | 11 | -- Recursion with a counter 12 | f3 :: Int -> [a] -> ([a], [a]) 13 | f3 _ [] = ([], []) 14 | f3 0 xs = ([], xs) 15 | f3 n (x:xs) = let (a, b) = f3 (pred n) xs in (x : a, b) 16 | 17 | -- Tail recursion with a counter 18 | f4 :: Int -> [a] -> ([a], [a]) 19 | f4 = f [] 20 | where f acc _ [] = (reverse acc, []) 21 | f acc 0 xs = (reverse acc, xs) 22 | f acc n (x:xs) = f (x : acc) (pred n) xs -------------------------------------------------------------------------------- /clojure/P13.clj: -------------------------------------------------------------------------------- 1 | ; P13 Run-length encoding of a list (direct solution). 2 | 3 | ; Factory function 4 | (defn encode [n x] 5 | (if (= 1 n) x [n x])) 6 | 7 | ; Using "split-with", so there's still some kind of sublists 8 | (defn f1 [l] 9 | (if (seq l) 10 | (let [h (first l) t (rest l) [a b] (split-with #(= % h) t)] 11 | (cons (encode (inc (count a)) h) (f1 b))) 12 | '())) 13 | 14 | ; Recursion, "look-behind" 15 | (defn f2 [l] 16 | (defn f [n x xs] 17 | (if (seq xs) 18 | (let [y (first xs) ys (rest xs)] 19 | (if (= y x) 20 | (f (inc n) y ys) 21 | (cons (encode n x) (f 1 y ys)))) 22 | (list (encode n x)))) 23 | (if (seq l) (f 1 (first l) (rest l)) '())) -------------------------------------------------------------------------------- /clojure/P17.clj: -------------------------------------------------------------------------------- 1 | ; P17 Split a list into two parts; the length of the first part is given. 2 | 3 | ; Using predefined function 4 | (def f1 split-at) 5 | 6 | ; Using "take" and "drop" 7 | (defn f2 [n l] 8 | [(take n l) (drop n l)]) 9 | 10 | ; Recursion with a counter 11 | (defn f3 [n l] 12 | (if (seq l) 13 | (if (zero? n) 14 | ['(), l] 15 | (let [[a b] (f3 (dec n) (rest l))] 16 | [(cons (first l) a), b])) 17 | ['(), '()])) 18 | 19 | ; Tail recursion with a counter 20 | (defn f4 [n l] 21 | (loop [k n xs l acc '()] 22 | (if (seq l) 23 | (if (zero? k) 24 | [(reverse acc) xs] 25 | (recur (dec k) (rest xs) (cons (first xs) acc))) 26 | [(reverse acc) '()]))) -------------------------------------------------------------------------------- /scala/P05.scala: -------------------------------------------------------------------------------- 1 | // P05 Reverse a list. 2 | 3 | // Predefined function 4 | def f0[T](list: List[T]): List[T] = list.reverse 5 | 6 | // Recursion (inefficient) 7 | def f1[T]: List[T] => List[T] = { 8 | case Nil => Nil 9 | case h :: t => f1(t) ::: h :: Nil 10 | } 11 | 12 | // Tail recursion 13 | @annotation.tailrec 14 | def f2[T](list: List[T], acc: List[T] = Nil): List[T] = list match { 15 | case Nil => acc 16 | case h :: t => f2(t, h :: acc) 17 | } 18 | 19 | // Folding 20 | def f3[T](list: List[T]): List[T] = 21 | list.foldLeft(Nil: List[T])((a, b) => b :: a) 22 | 23 | // Imperative 24 | def f4[T](list: List[T]): List[T] = { 25 | var acc: List[T] = Nil 26 | for(each <- list) acc ::= each 27 | acc 28 | } -------------------------------------------------------------------------------- /clojure/P10.clj: -------------------------------------------------------------------------------- 1 | ; P10 Run-length encoding of a list. 2 | 3 | ; Mapping 4 | (defn f1 [ls] 5 | (map (fn [l] [(count l) (first l)]) ls)) 6 | 7 | ; Mapping, again 8 | (defn f2 [ls] 9 | (map vector (map count ls) (map first ls))) 10 | 11 | ; Folding 12 | (defn f3 [ls] 13 | (reduce (fn [acc l] (cons [(count l) (first l)] acc)) '() (reverse ls))) 14 | 15 | ; Recursion 16 | (defn f4 [ls] 17 | (if (seq ls) 18 | (let [h (first ls) t (rest ls)] 19 | (cons [(count h) (first h)] (f4 t))) 20 | '())) 21 | 22 | ; Tail recursion 23 | (defn f5 [ls] 24 | (loop [acc '() l ls] 25 | (if (seq l) 26 | (let [h (first l) t (rest l)] 27 | (recur (cons [(count h) (first h)] acc) t)) 28 | (reverse acc)))) -------------------------------------------------------------------------------- /java/P09.java: -------------------------------------------------------------------------------- 1 | // P09 Pack consecutive duplicates of list elements into sublists. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P09 { 8 | // Iteration 9 | List> f1(List list) { 10 | if (list.isEmpty()) return nil(); 11 | 12 | List> result = nil(); 13 | List value = nil(); 14 | for (T each : list) { 15 | if (value.isEmpty() || value.head() == each) { 16 | value = cons(each, value); 17 | } else { 18 | result = cons(value, result); 19 | value = singleton(each); 20 | } 21 | } 22 | 23 | return result.reverse(); 24 | } 25 | } -------------------------------------------------------------------------------- /java/P12.java: -------------------------------------------------------------------------------- 1 | // P12 Decode a run-length encoded list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | import static core.Pair.*; 8 | 9 | class P12 { 10 | // Imperative, list of objects 11 | @SuppressWarnings("unchecked") 12 | List f1(List list) { 13 | List acc = nil(); 14 | for (Object each : list) { 15 | if (each instanceof Pair) { 16 | Pair pair = (Pair) each; 17 | acc = concat(List.replicate(pair.getA(), pair.getB()), acc); 18 | } else { 19 | acc = cons(each, acc); 20 | } 21 | } 22 | return acc.reverse(); 23 | } 24 | } -------------------------------------------------------------------------------- /haskell/p06.hs: -------------------------------------------------------------------------------- 1 | -- P06 Find out whether a list is a palindrome. 2 | -- A palindrome can be read forward or backward; e.g. (x a m a x). 3 | 4 | -- Recursion (inefficient) 5 | f1 :: (Eq a) => [a] -> Bool 6 | f1 [] = True 7 | f1 [_] = True 8 | f1 xs = (head xs) == (last xs) && (f1 $ init $ tail xs) 9 | 10 | -- Using "reverse" function 11 | f2 :: (Eq a) => [a] -> Bool 12 | f2 xs = xs == reverse xs 13 | 14 | -- Zip 15 | f3 :: (Eq a) => [a] -> Bool 16 | f3 xs = all (uncurry (==)) $ zip xs (reverse xs) 17 | 18 | -- ZipWith 19 | f4 :: (Eq a) => [a] -> Bool 20 | f4 xs = all id $ zipWith (==) xs (reverse xs) 21 | 22 | -- ZipWith plus folding 23 | f5 :: (Eq a) => [a] -> Bool 24 | f5 xs = foldr (&&) True $ zipWith (==) xs (reverse xs) -------------------------------------------------------------------------------- /scala/P04.scala: -------------------------------------------------------------------------------- 1 | // P04 Find the number of elements of a list. 2 | 3 | // Predefined function 4 | def f0[T](list: List[T]): Int = list.length 5 | 6 | // Recursion 7 | def f1[T]: List[T] => Int = { 8 | case Nil => 0 9 | case _ :: t => 1 + f1(t) 10 | } 11 | 12 | // Tail recursion 13 | @annotation.tailrec 14 | def f2[T](list: List[T], n: Int = 0): Int = list match { 15 | case Nil => n 16 | case _ :: t => f2(t, n + 1) 17 | } 18 | 19 | // Folding 20 | def f3[T](list: List[T]): Int = list.foldLeft(0)((a, _) => a + 1) 21 | 22 | // Using build-in 'sum' 23 | def f4[T](list: List[T]): Int = list.map(_ => 1).sum 24 | 25 | // With 'view' to avoid the creation of a temporary list 26 | def f5[T](list: List[T]): Int = list.view.map(_ => 1).sum -------------------------------------------------------------------------------- /java/P19.java: -------------------------------------------------------------------------------- 1 | // P19 Rotate a list N places to the left. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | 8 | class P19 { 9 | // Using "splitAt" 10 | List f1(List list, int n) { 11 | int l = list.length(); 12 | int i = list.nonEmpty() ? n % l : 0; 13 | Pair, List> p = list.splitAt(i < 0 ? l + i : i); 14 | return concat(p.getB(), p.getA()); 15 | } 16 | 17 | // Tail recursion 18 | List f2(List list, int n) { 19 | if (list.isEmpty()) return nil(); 20 | if (n == 0) return list; 21 | return n > 0 ? f2(concat(list.tail(), singleton(list.head())), n - 1) : 22 | f2(cons(list.last(), list.init()), n + 1); 23 | } 24 | } -------------------------------------------------------------------------------- /scala/P20.scala: -------------------------------------------------------------------------------- 1 | // P20 Remove the K'th element from a list. 2 | 3 | // Using "splitAt" 4 | def f1[T](list: List[T], n: Int): (List[T], T) = { 5 | val (a, x :: b) = list.splitAt(n - 1) 6 | (a ::: b, x) 7 | } 8 | 9 | // By index (inefficient) 10 | def f2[T](list: List[T], n: Int): (List[T], T) = 11 | (list.take(n - 1) ::: list.drop(n), list(n - 1)) 12 | 13 | // Recursion 14 | def f3[T](list: List[T], n: Int): (List[T], T) = { 15 | val h :: t = list 16 | if (n > 1) { 17 | val (a, b) = f3(t, n - 1) 18 | (h :: a, b) 19 | } else { 20 | (t, h) 21 | } 22 | } 23 | 24 | // Tail recursion 25 | @annotation.tailrec 26 | def f4[T](list: List[T], n: Int, acc: List[T] = Nil): (List[T], T) = { 27 | val h :: t = list 28 | if (n > 1) f4(t, n - 1, h :: acc) else (acc.reverse ::: t, h) 29 | } -------------------------------------------------------------------------------- /java/P04.java: -------------------------------------------------------------------------------- 1 | // P04 Find the number of elements of a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P04 { 8 | // "Predefined" function 9 | int f0(List list) { 10 | return list.length(); 11 | } 12 | 13 | // Recursion 14 | int f1(List list) { 15 | return list.isEmpty() ? 0 : 1 + f1(list.tail()); 16 | } 17 | 18 | // Tail recursion 19 | int f2(List list) { 20 | return f2_inner(list, 0); 21 | } 22 | 23 | private int f2_inner(List list, int n) { 24 | return list.isEmpty() ? n : f2_inner(list.tail(), n + 1); 25 | } 26 | 27 | // Iteration 28 | int f3(List list) { 29 | int n = 0; 30 | for (T x : list) n++; 31 | return n; 32 | } 33 | } -------------------------------------------------------------------------------- /java/P15.java: -------------------------------------------------------------------------------- 1 | // P15 Replicate the elements of a list a given number of times. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P15 { 8 | // Recursion, one-pass concatenation 9 | List f1(int n, List list) { 10 | return list.isEmpty() 11 | ? List.nil() 12 | : prepend(n, list.head(), f1(n, list.tail())); 13 | } 14 | 15 | List prepend(int n, T x, List list) { 16 | return n == 0 ? list : cons(x, prepend(n - 1, x, list)); 17 | } 18 | 19 | // Imperative 20 | List f2(int n, List list) { 21 | List acc = nil(); 22 | for (T each : list) 23 | for (int i = 0; i < n; i++) 24 | acc = cons(each, acc); 25 | return acc.reverse(); 26 | } 27 | } -------------------------------------------------------------------------------- /scala/P06.scala: -------------------------------------------------------------------------------- 1 | // P06 Find out whether a list is a palindrome. 2 | // A palindrome can be read forward or backward; e.g. (x a m a x). 3 | 4 | // Recursion (inefficient) 5 | def f1[T]: List[T] => Boolean = { 6 | case Nil => true 7 | case _ :: Nil => true 8 | case xs => xs.head == xs.last && f1(xs.tail.init) 9 | } 10 | 11 | // Builtin functions 12 | def f2[T](list: List[T]): Boolean = list == list.reverse 13 | 14 | // Zip 15 | def f3[T](list: List[T]): Boolean = 16 | list.zip(list.reverse).forall{case (a, b) => a == b} 17 | 18 | // Zip again 19 | def f4[T](list: List[T]): Boolean = 20 | list.zip(list.reverse).forall(((_: T) == (_: T)).tupled) 21 | 22 | // Zip with folding 23 | def f5[T](list: List[T]): Boolean = 24 | list.zip(list.reverse) 25 | .map{case (a, b) => a == b} 26 | .foldLeft(true)(_ && _) -------------------------------------------------------------------------------- /java/P11.java: -------------------------------------------------------------------------------- 1 | // P11 Modified run-length encoding. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | import static core.Pair.*; 8 | 9 | class P11 { 10 | // Recursion, list of objects 11 | @SuppressWarnings("unchecked") 12 | List f1(List> list) { 13 | if (list.isEmpty()) return nil(); 14 | Pair h = list.head(); 15 | return cons(h.getA().equals(1) ? h.getB() : h, f1(list.tail())); 16 | } 17 | 18 | // Imperative, list of objects 19 | @SuppressWarnings("unchecked") 20 | List f2(List> list) { 21 | List acc = nil(); 22 | for (Pair each : list) 23 | acc = cons(each.getA().equals(1) ? each.getB() : each, acc); 24 | return acc.reverse(); 25 | } 26 | } -------------------------------------------------------------------------------- /haskell/p16.hs: -------------------------------------------------------------------------------- 1 | -- P16 Drop every N'th element from a list. 2 | 3 | -- Recursion with a counter 4 | f1 :: Int -> [a] -> [a] 5 | f1 n = f n 6 | where f _ [] = [] 7 | f 1 (_:xs) = f n xs 8 | f k (x:xs) = x : f (pred k) xs 9 | 10 | -- Tail recursion 11 | f2 :: Int -> [a] -> [a] 12 | f2 n = f n [] 13 | where f _ acc [] = reverse acc 14 | f 1 acc (_:xs) = f n acc xs 15 | f k acc (x:xs) = f (pred k) (x : acc) xs 16 | 17 | -- Recursion with "take" and "drop" 18 | f3 :: Int -> [a] -> [a] 19 | f3 _ [] = [] 20 | f3 n xs = take (pred n) xs ++ (f2 n $ drop n xs) 21 | 22 | -- Zip with cycle, filter, map 23 | f4 :: Int -> [a] -> [a] 24 | f4 n = map snd . filter ((< n) . fst) . zip (cycle [1..n]) 25 | 26 | -- Using list comprehensions 27 | f5 :: Int -> [a] -> [a] 28 | f5 n xs = [x | (x, k) <- zip xs $ cycle [1..n], k < n] -------------------------------------------------------------------------------- /clojure/P16.clj: -------------------------------------------------------------------------------- 1 | ; P16 Drop every N'th element from a list. 2 | 3 | ; Recursion with a counter 4 | (defn f1 [n l] 5 | (defn f [k xs] 6 | (if (seq xs) 7 | (if (= k 1) 8 | (f n (rest xs)) 9 | (cons (first xs) (f (dec k) (rest xs)))) 10 | '())) 11 | (f n l)) 12 | 13 | ; Tail recursion with a counter 14 | (defn f2 [n l] 15 | (loop [k n acc '() xs l] 16 | (if (seq xs) 17 | (if (= k 1) 18 | (recur n acc (rest xs)) 19 | (recur (dec k) (cons (first xs) acc) (rest xs))) 20 | (reverse acc)))) 21 | 22 | ; Recursion with "take" and "drop" 23 | (defn f3 [n l] 24 | (if (seq l) 25 | (concat (take (dec n) l) (f3 n (drop n l))) 26 | '())) 27 | 28 | ; Zip with cycle, filter, map 29 | (defn f4 [n l] 30 | (map first 31 | (filter #(< (second %) n) 32 | (map list l (cycle (range 1 (inc n))))))) -------------------------------------------------------------------------------- /scala/P17.scala: -------------------------------------------------------------------------------- 1 | // P17 Split a list into two parts; the length of the first part is given. 2 | 3 | // Using predefined function 4 | def f1[T](n: Int, xs: List[T]): (List[T], List[T]) = 5 | xs.splitAt(n) 6 | 7 | // Using "take" and "drop" 8 | def f2[T](n: Int, xs: List[T]): (List[T], List[T]) = 9 | (xs.take(n), xs.drop(n)) 10 | 11 | // Recursion with a counter 12 | def f3[T]: (Int, List[T]) => (List[T], List[T]) = { 13 | case (_, Nil) => (Nil, Nil) 14 | case (0, xs) => (Nil, xs) 15 | case (n, x :: xs) => 16 | val (a, b) = f3(n - 1, xs) 17 | (x :: a, b) 18 | } 19 | 20 | // Tail recursion with a counter 21 | @annotation.tailrec 22 | def f4[T](n: Int, xs: List[T], acc: List[T] = Nil): (List[T], List[T]) = (n, xs) match { 23 | case (_, Nil) => (acc.reverse, Nil) 24 | case (0, xs) => (acc.reverse, xs) 25 | case (n, x :: xs) => f4(n - 1, xs, x :: acc) 26 | } -------------------------------------------------------------------------------- /scala/P02.scala: -------------------------------------------------------------------------------- 1 | // P02 Find the last but one element of a list. 2 | 3 | // Tail recursion 4 | @annotation.tailrec 5 | def f1[T](list: List[T]): T = list match { 6 | case Nil => throw new NoSuchElementException("List is empty") 7 | case List(_) => throw new NoSuchElementException("Sigleton list") 8 | case List(x, _) => x 9 | case _ :: xs => f1(xs) 10 | } 11 | 12 | // Function application 13 | def f2[T](list: List[T]): T = list.init.last 14 | 15 | // With errors check 16 | def f3[T](list: List[T]): T = list.init.lastOption.getOrElse(throw new NoSuchElementException()) 17 | 18 | // Function composition 19 | def f4[T] = ((_: List[T]).last).compose((_: List[T]).init) 20 | 21 | // Using index 22 | def f5[T](list: List[T]): T = list.reverse(1) 23 | 24 | // With partial function lifting 25 | def f6[T](list: List[T]): T = list.reverse.lift(1).getOrElse(throw new NoSuchElementException()) -------------------------------------------------------------------------------- /scala/P22.scala: -------------------------------------------------------------------------------- 1 | // P22 Create a list containing all integers within a given range. 2 | 3 | // Through predefined "Range" 4 | def f1(a: Int, b: Int): List[Int] = 5 | (a to b).toList 6 | 7 | // A part of an infinite list 8 | def f2(a: Int, b: Int): List[Int] = 9 | Stream.iterate(a)(1 +).take(b - a + 1).toList 10 | 11 | // As a sum 12 | def f3(a: Int, b: Int): List[Int] = 13 | List.fill(b - a)(1).scan(a)(_ + _) 14 | 15 | // Recursion 16 | def f4(a: Int, b: Int): List[Int] = 17 | if (a <= b) a :: f4(a + 1, b) else Nil 18 | 19 | // Tail recursion 20 | @annotation.tailrec 21 | def f5(a: Int, b: Int, acc: List[Int] = Nil): List[Int] = 22 | if (b >= a) f5(a, b - 1, b :: acc) else acc 23 | 24 | // Imperative 25 | def f6(a: Int, b: Int): List[Int] = { 26 | var i = b 27 | var result: List[Int] = Nil 28 | while (i >= a) { 29 | result ::= i 30 | i -= 1 31 | } 32 | result 33 | } -------------------------------------------------------------------------------- /java/P24.java: -------------------------------------------------------------------------------- 1 | // P24 Lotto: Draw N different random numbers from the set 1..M. 2 | 3 | import core.List; 4 | 5 | import java.util.HashSet; 6 | import java.util.Random; 7 | import java.util.Set; 8 | 9 | import static core.List.*; 10 | 11 | class P24 { 12 | private final Random random = new Random(); 13 | 14 | // The obvious answer is P23.f1(n, range(1, m)) 15 | // Let's use a Set with distinct values for a different solution 16 | List f1(int n, int m) { 17 | List result = nil(); 18 | 19 | Set buffer = new HashSet(); 20 | 21 | for (int i = 0; i < n; i++) { 22 | int x; 23 | do { 24 | x = 1 + random.nextInt(m); 25 | } while (buffer.contains(x)); 26 | 27 | buffer.add(x); 28 | result = cons(x, result); 29 | } 30 | 31 | return result; 32 | } 33 | } -------------------------------------------------------------------------------- /haskell/p22.hs: -------------------------------------------------------------------------------- 1 | -- P22 Create a list containing all integers within a given range. 2 | 3 | import Data.List 4 | 5 | -- Predefined function 6 | f1 :: Int -> Int -> [Int] 7 | f1 = enumFromTo 8 | 9 | -- Range syntax 10 | f2 :: Int -> Int -> [Int] 11 | f2 a b = [a..b] 12 | 13 | -- A part of an infinite list 14 | f3 :: Int -> Int -> [Int] 15 | f3 a b = take (succ b - a) $ iterate succ a 16 | 17 | -- Unfolding 18 | f4 :: Int -> Int -> [Int] 19 | f4 a b = unfoldr (\n -> if (n <= b) then Just (n, succ (n)) else Nothing) a 20 | 21 | -- As a sum 22 | f5 :: Int -> Int -> [Int] 23 | f5 a b = scanl (+) a $ replicate (b - a) 1 24 | 25 | -- Recursion 26 | f6 :: Int -> Int -> [Int] 27 | f6 a b 28 | | a <= b = a : f6 (succ a) b 29 | | otherwise = [] 30 | 31 | -- Tail recursion 32 | f7 :: Int -> Int -> [Int] 33 | f7 = f [] 34 | where f acc a b 35 | | b >= a = f (b : acc) a (pred b) 36 | | otherwise = acc -------------------------------------------------------------------------------- /java/P22.java: -------------------------------------------------------------------------------- 1 | // P22 Create a list containing all integers within a given range. 2 | 3 | import core.List; 4 | 5 | import static core.List.cons; 6 | import static core.List.nil; 7 | 8 | class P22 { 9 | // Recursion 10 | List f1(int a, int b) { 11 | return a <= b ? cons(a, f1(a + 1, b)) : List.nil(); 12 | } 13 | 14 | // Tail recursion 15 | List f2(int a, int b) { 16 | return f2_inner(a, b, List.nil()); 17 | } 18 | 19 | private List f2_inner(int a, int b, List acc) { 20 | return b >= a ? f2_inner(a, b - 1, cons(b, acc)) : acc; 21 | } 22 | 23 | // Imperative 24 | List f3(int a, int b) { 25 | int i = b; 26 | List result = nil(); 27 | while (i >= a) { 28 | result = cons(i, result); 29 | i--; 30 | } 31 | return result; 32 | } 33 | } -------------------------------------------------------------------------------- /haskell/p13.hs: -------------------------------------------------------------------------------- 1 | -- P13 Run-length encoding of a list (direct solution). 2 | 3 | data Entry a = Value a | Sequence Int a deriving Show 4 | 5 | -- Factory function 6 | makeEntry :: Int -> a -> Entry a 7 | makeEntry 1 a = Value a 8 | makeEntry n a = Sequence n a 9 | 10 | -- A simple solution, but there's still some kind of sublists 11 | f1 :: Eq a => [a] -> [Entry a] 12 | f1 [] = [] 13 | f1 (x:xs) = let (a, b) = span (== x) xs in 14 | makeEntry (succ $ length a) x : f1 b 15 | 16 | -- Recursion, "look-ahead" 17 | f2 :: Eq a => [a] -> [Entry a] 18 | f2 [] = [] 19 | f2 xs = f 1 xs 20 | where f n [x] = [makeEntry n x] 21 | f n (a:bs@(b:_)) = if a == b then f (succ n) bs else makeEntry n a : f 1 bs 22 | 23 | -- Recursion, "look-behind" 24 | f3 :: Eq a => [a] -> [Entry a] 25 | f3 [] = [] 26 | f3 (x:xs) = f 1 x xs 27 | where f n x [] = [makeEntry n x] 28 | f n x (y:ys) = if y == x then f (succ n) y ys else makeEntry n x : f 1 y ys -------------------------------------------------------------------------------- /java/P13.java: -------------------------------------------------------------------------------- 1 | // P13 Run-length encoding of a list (direct solution). 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | import static core.Pair.*; 7 | 8 | class P13 { 9 | // Imperative, list of objects 10 | @SuppressWarnings("unchecked") 11 | List f1(List list) { 12 | if (list.isEmpty()) return nil(); 13 | 14 | List acc = nil(); 15 | Object x = list.head(); 16 | int n = 1; 17 | 18 | for (Object each : list.tail()) { 19 | if (each.equals(x)) { 20 | n++; 21 | } else { 22 | acc = cons(makeValue(n, x), acc); 23 | x = each; 24 | n = 1; 25 | } 26 | } 27 | 28 | acc = cons(makeValue(n, x), acc); 29 | 30 | return acc.reverse(); 31 | } 32 | 33 | // Factory method 34 | private Object makeValue(int n, Object x) { 35 | return n == 1 ? x : pair(n, x); 36 | } 37 | } -------------------------------------------------------------------------------- /java/core/Pair.java: -------------------------------------------------------------------------------- 1 | package core; 2 | 3 | // Immutable Tuple2 4 | public class Pair { 5 | private A a; 6 | private B b; 7 | 8 | private Pair(A a, B b) { 9 | this.a = a; 10 | this.b = b; 11 | } 12 | 13 | public A getA() { 14 | return a; 15 | } 16 | 17 | public B getB() { 18 | return b; 19 | } 20 | 21 | public static Pair pair(A a, B b) { 22 | return new Pair(a, b); 23 | } 24 | 25 | @Override 26 | public boolean equals(Object o) { 27 | return o instanceof Pair && a.equals(((Pair) o).a) && b.equals(((Pair) o).b); 28 | } 29 | 30 | @Override 31 | public int hashCode() { 32 | int result = a.hashCode(); 33 | result = 31 * result + b.hashCode(); 34 | return result; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return String.format("(%s, %s)", a.toString(), b.toString()); 40 | } 41 | } -------------------------------------------------------------------------------- /scala/P08.scala: -------------------------------------------------------------------------------- 1 | // P08 Eliminate consecutive duplicates of list elements. 2 | 3 | // Recursion with "dropWhile" 4 | def f1[T]: List[T] => List[T] = { 5 | case Nil => Nil 6 | case h :: t => h :: f1(t.dropWhile(h ==)) 7 | } 8 | 9 | // Tail recursion with "dropWhile" 10 | @annotation.tailrec 11 | def f2[T](list: List[T], acc: List[T] = Nil): List[T] = list match { 12 | case Nil => acc.reverse 13 | case h :: t => f2(t.dropWhile(h ==), h :: acc) 14 | } 15 | 16 | // Recursion with pattern matching 17 | def f3[T]: List[T] => List[T] = { 18 | case a :: (bs@(b :: _)) => if (a == b) f3(bs) else a :: f3(bs) 19 | case xs => xs 20 | } 21 | 22 | // Folding 23 | def f4[T]: List[T] => List[T] = { 24 | case Nil => Nil 25 | case l => l.foldRight(List(l.last))((b, a) => if (a.head == b) a else b :: a) 26 | } 27 | 28 | // Using "zip" 29 | def f5[T]: List[T] => List[T] = { 30 | case Nil => Nil 31 | case xs@(x :: _) => x :: xs.zip(xs.tail).filter(p => p._1 != p._2).map(_._2) 32 | } -------------------------------------------------------------------------------- /scala/P21.scala: -------------------------------------------------------------------------------- 1 | // P21 Insert an element at a given position into a list. 2 | 3 | // Using "splitAt" 4 | def f1[T](list: List[T], n: Int, x: T): List[T] = { 5 | val (a, b) = list.splitAt(n - 1) 6 | (a ::: x :: b) 7 | } 8 | 9 | // By index (inefficient) 10 | def f2[T](list: List[T], n: Int, x: T): List[T] = 11 | list.take(n - 1) ::: x :: list.drop(n - 1) 12 | 13 | // Recursion 14 | def f3[T](list: List[T], n: Int, x: T): List[T] = 15 | if (n == 1) x :: list else list.head :: f3(list.tail, n - 1, x) 16 | 17 | // Tail recursion 18 | @annotation.tailrec 19 | def f4[T](list: List[T], n: Int, x: T, acc: List[T] = Nil): List[T] = 20 | if (n == 1) acc.reverse ::: x :: list else f4(list.tail, n - 1, x, list.head :: acc) 21 | 22 | // Imperative 23 | def f5[T](list: List[T], n: Int, x: T, acc: List[T] = Nil): List[T] = { 24 | var result: List[T] = Nil 25 | var i = 0 26 | for (each <- list) { 27 | i += 1 28 | result = if (i == 1) x :: each :: result else each :: result 29 | } 30 | result.reverse 31 | } -------------------------------------------------------------------------------- /java/P05.java: -------------------------------------------------------------------------------- 1 | // P05 Reverse a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P05 { 8 | // "Predefined" function 9 | List f0(List list) { 10 | return list.reverse(); 11 | } 12 | 13 | // Recursion (inefficient) 14 | List f1(List list) { 15 | return list.isEmpty() 16 | ? List.nil() 17 | : concat(f1(list.tail()), singleton(list.head())); 18 | } 19 | 20 | // Tail recursion 21 | List f2(List list) { 22 | return f2_inner(list, List.nil()); 23 | } 24 | 25 | private List f2_inner(List list, List acc) { 26 | return list.isEmpty() 27 | ? acc 28 | : f2_inner(list.tail(), cons(list.head(), acc)); 29 | } 30 | 31 | // Imperative 32 | List f3(List list) { 33 | List acc = nil(); 34 | for (T each : list) acc = cons(each, acc); 35 | return acc; 36 | } 37 | } -------------------------------------------------------------------------------- /haskell/p08.hs: -------------------------------------------------------------------------------- 1 | -- P08 Eliminate consecutive duplicates of list elements. 2 | 3 | import Data.List 4 | 5 | -- Built-in functions composition 6 | f1 :: Eq a => [a] -> [a] 7 | f1 = map head . group 8 | 9 | -- Recursion with dropWhile 10 | f2 :: Eq a => [a] -> [a] 11 | f2 [] = [] 12 | f2 (x:xs) = x : (f2 $ dropWhile (== x) xs) 13 | 14 | -- Recursion with pattern matching (look-ahead) 15 | f3 :: Eq a => [a] -> [a] 16 | f3 (a:(bs@(b:_))) 17 | | a == b = f3 bs 18 | | otherwise = a : f3 bs 19 | f3 xs = xs 20 | 21 | -- Tail recursion (look-behind) 22 | f4 :: Eq a => [a] -> [a] 23 | f4 = f4' [] 24 | where f4' acc [] = reverse acc 25 | f4' [] (x:xs) = f4' [x] xs 26 | f4' ys@(y:_) (x:xs) = if y == x then f4' ys xs else f4' (x : ys) xs 27 | 28 | -- List folding 29 | f5 :: Eq a => [a] -> [a] 30 | f5 [] = [] 31 | f5 xs = foldr (\a b -> if a == (head b) then b else a : b) [last xs] xs 32 | 33 | -- Using "zip" 34 | f6 :: Eq a => [a] -> [a] 35 | f6 [] = [] 36 | f6 xs@(x:_) = x : map snd (filter (uncurry (/=)) (zip xs (tail xs))) -------------------------------------------------------------------------------- /java/P08.java: -------------------------------------------------------------------------------- 1 | // P08 Eliminate consecutive duplicates of list elements. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P08 { 8 | // Recursion 9 | List f1(List list) { 10 | if (list.nonEmpty() && list.tail().nonEmpty()) { 11 | T a = list.head(); 12 | T b = list.tail().head(); 13 | List t = list.tail(); 14 | return a == b ? f1(t) : cons(a, f1(t)); 15 | } else { 16 | return list; 17 | } 18 | } 19 | 20 | // Iteration 21 | List f2(List list) { 22 | List result = nil(); 23 | T previous = null; 24 | boolean first = true; 25 | for (T each : list) { 26 | if (first) { 27 | result = cons(each, result); 28 | first = false; 29 | } else if (each != previous) { 30 | result = cons(each, result); 31 | } 32 | previous = each; 33 | } 34 | 35 | return result.reverse(); 36 | } 37 | } -------------------------------------------------------------------------------- /haskell/p14.hs: -------------------------------------------------------------------------------- 1 | -- P14 Duplicate the elements of a list. 2 | 3 | -- Recursion 4 | f1 :: [a] -> [a] 5 | f1 [] = [] 6 | f1 (x:xs) = x : x : f1 xs 7 | 8 | -- Direct tail recursion (inefficient) 9 | f2 :: [a] -> [a] 10 | f2 = f [] 11 | where f acc [] = acc 12 | f acc (x:xs) = f (acc ++ [x, x]) xs 13 | 14 | -- Tail recursion with "reverse" 15 | f3 :: [a] -> [a] 16 | f3 = reverse . f [] 17 | where f acc [] = acc 18 | f acc (x:xs) = f (x : x : acc) xs 19 | 20 | -- Right folding 21 | f4 :: [a] -> [a] 22 | f4 = foldr (\x xs -> x : x : xs) [] 23 | 24 | -- Direct left folding (inefficient) 25 | f5 :: [a] -> [a] 26 | f5 = foldl (\xs x -> xs ++ [x, x]) [] 27 | 28 | -- Left folding with reverse 29 | f6 :: [a] -> [a] 30 | f6 = reverse . foldl (\xs x -> x : x : xs) [] 31 | 32 | -- Map with "replicate" then concatenate 33 | f7 :: [a] -> [a] 34 | f7 = concat . map (replicate 2) 35 | 36 | -- Using concatMap 37 | f8 :: [a] -> [a] 38 | f8 = concatMap (\x -> [x, x]) 39 | 40 | -- Using concatMap with "replicate" 41 | f9 :: [a] -> [a] 42 | f9 = concatMap (replicate 2) -------------------------------------------------------------------------------- /scala/P10.scala: -------------------------------------------------------------------------------- 1 | // P10 Run-length encoding of a list. 2 | 3 | // Mapping 4 | def f1[T](list: List[List[T]]): List[(Int, T)] = 5 | list.map(l => (l.length, l.head)) 6 | 7 | // Mapping with "zip" 8 | def f2[T](list: List[List[T]]): List[(Int, T)] = 9 | list.map(_.length).zip(list.map(_.head)) 10 | 11 | // Folding (underlying implementation is recursive) 12 | def f3[T](list: List[List[T]]): List[(Int, T)] = 13 | list.foldRight(Nil: List[(Int, T)])((x, acc) => (x.length, x.head) :: acc) 14 | 15 | // Folding (underlying implementation is iterative) 16 | def f4[T](list: List[List[T]]): List[(Int, T)] = 17 | list.reverse.foldLeft(Nil: List[(Int, T)])((acc, x) => (x.length, x.head) :: acc) 18 | 19 | // Recursion 20 | def f5[T]: List[List[T]] => List[(Int, T)] = { 21 | case Nil => Nil 22 | case h :: t => (h.length, h.head) :: f5(t) 23 | } 24 | 25 | // Tail recursion 26 | @annotation.tailrec 27 | def f6[T](list: List[List[T]], acc: List[(Int, T)] = Nil): List[(Int, T)] = list match { 28 | case Nil => acc.reverse 29 | case h :: t => f6(t, (h.length, h.head) :: acc) 30 | } -------------------------------------------------------------------------------- /clojure/P14.clj: -------------------------------------------------------------------------------- 1 | ; P14 Duplicate the elements of a list. 2 | 3 | ; Recursion 4 | (defn f1 [l] 5 | (if (seq l) 6 | (cons (first l) 7 | (cons (first l) (f1 (rest l)))) 8 | '())) 9 | 10 | ; Direct tail recursion (inefficient) 11 | (defn f2 [l] 12 | (loop [acc '() xs l] 13 | (if (seq xs) 14 | (recur 15 | (concat acc (list (first xs) (first xs))) 16 | (rest xs)) 17 | acc))) 18 | 19 | ; Tail recursion with "reverse" 20 | (defn f3 [l] 21 | (loop [acc '() xs l] 22 | (if (seq xs) 23 | (recur 24 | (cons (first xs) (cons (first xs) acc)) 25 | (rest xs)) 26 | (reverse acc)))) 27 | 28 | ; Direct left folding (inefficient) 29 | (defn f4 [l] 30 | (reduce #(concat %1 (list %2 %2)) '() l)) 31 | 32 | ; Left folding with reverse 33 | (defn f5 [l] 34 | (reduce #(cons %2 (cons %2 %1)) '() (reverse l))) 35 | 36 | ; Map then flatten 37 | (defn f6 [l] 38 | (flatten (map #(list %1 %1) l))) 39 | 40 | ; Using "mapcat" 41 | (defn f7 [l] 42 | (mapcat #(list %1 %1) l)) 43 | 44 | ; With "repeat" 45 | (defn f8 [l] 46 | (mapcat #(repeat 2 %) l)) -------------------------------------------------------------------------------- /clojure/P18.clj: -------------------------------------------------------------------------------- 1 | ; P18 Extract a slice from a list. 2 | 3 | ; Using "take" and "drop" 4 | (defn f1 [l i k] 5 | (drop (dec i) (take k l))) 6 | 7 | ; Using "split-at" 8 | (defn f2 [l i k] 9 | (second (split-at (dec i) (first (split-at k l))))) 10 | 11 | ; Recursion 12 | (defn f3 [l i k] 13 | (if (seq l) 14 | (if (> i 1) 15 | (f3 (rest l) (dec i) (dec k)) 16 | (if (pos? k) 17 | (cons (first l) (f3 (rest l) 1 (dec k))) 18 | '())) 19 | '())) 20 | 21 | ; Tail recursion 22 | (defn f4 [l i k] 23 | (loop [acc '() xs l a i b k] 24 | (if (seq xs) 25 | (if (> a 1) 26 | (recur acc (rest xs) (dec a) (dec b)) 27 | (if (pos? b) 28 | (recur (cons (first xs) acc) (rest xs) 1 (dec b)) 29 | (reverse acc))) 30 | (reverse acc)))) 31 | 32 | ; Filter by index 33 | (defn f5 [l i k] 34 | (map first 35 | (filter #(>= (second %) i) 36 | (map list l (range 1 (inc k)))))) 37 | 38 | ; Folding 39 | (defn f6 [l i k] 40 | (defn f [acc [x n]] 41 | (if (>= n i) (cons x acc) acc)) 42 | (reverse 43 | (reduce f '() (map list l (range 1 (inc k)))))) -------------------------------------------------------------------------------- /scala/P01.scala: -------------------------------------------------------------------------------- 1 | // P01 Find the last element of a list. 2 | 3 | // Predefined function 4 | def f0[T](list: List[T]): T = list.last 5 | 6 | // Tail recursion 7 | @annotation.tailrec 8 | def f1[T](list: List[T]): T = list match { 9 | case h :: Nil => h 10 | case _ :: t => f1(t) 11 | case _ => throw new NoSuchElementException("List is empty") 12 | } 13 | 14 | // Chained calls 15 | def f2[T](list: List[T]): T = list.reverse.head 16 | 17 | // Haskell-like function composition, point-free style (looks strange with Scala syntax and OO model) 18 | def f3[T] = ((_: List[T]).head).compose((_: List[T]).reverse) 19 | 20 | // Reversed function composition 21 | def f4[T] = ((_: List[T]).reverse).andThen((_: List[T]).head) 22 | 23 | // Java-like implementation with side effects 24 | def f5[T](list: List[T]): T = { 25 | var result: Option[T] = None 26 | for (each <- list) result = Some(each) 27 | result.getOrElse(throw new NoSuchElementException("List is empty")) 28 | } 29 | 30 | // Folding 31 | def f6[T](list: List[T]): T = if (list.nonEmpty) list.reduce((a, b) => b) else 32 | throw new NoSuchElementException("List is empty") -------------------------------------------------------------------------------- /haskell/p18.hs: -------------------------------------------------------------------------------- 1 | -- P18 Extract a slice from a list. 2 | 3 | -- Using "take" and "drop" 4 | f1 :: [a] -> Int -> Int -> [a] 5 | f1 xs i k = drop (pred i) $ take k xs 6 | 7 | -- Using "splitAt" 8 | f2 :: [a] -> Int -> Int -> [a] 9 | f2 xs i k = snd $ splitAt (pred i) $ fst $ splitAt k xs 10 | 11 | -- Recursion 12 | f3 :: [a] -> Int -> Int -> [a] 13 | f3 [] _ _ = [] 14 | f3 (x:xs) i k 15 | | i > 1 = f3 xs (pred i) (pred k) 16 | | k > 0 = x : f3 xs 1 (pred k) 17 | | otherwise = [] 18 | 19 | -- Tail recursion 20 | f4 :: [a] -> Int -> Int -> [a] 21 | f4 xs i k = reverse $ f [] xs i k 22 | where f acc [] _ _ = acc 23 | f acc (x : xs) i k 24 | | i > 1 = f acc xs (pred i) (pred k) 25 | | k > 0 = f (x : acc) xs 1 (pred k) 26 | | otherwise = acc 27 | 28 | -- Filter by index 29 | f5 :: [a] -> Int -> Int -> [a] 30 | f5 xs i k = fst $ unzip $ filter ((>=i) . snd) $ zip xs [1..k] 31 | 32 | -- List comprehension 33 | f6 :: [a] -> Int -> Int -> [a] 34 | f6 xs i k = [x | (x, n) <- zip xs [1..k], n >= i] 35 | 36 | -- Folding 37 | f7 :: [a] -> Int -> Int -> [a] 38 | f7 xs i k = foldr f [] $ zip xs [1..k] 39 | where f (x, n) acc 40 | | n >=i = x : acc 41 | | otherwise = acc -------------------------------------------------------------------------------- /scala/P14.scala: -------------------------------------------------------------------------------- 1 | // P14 Duplicate the elements of a list. 2 | 3 | // Recursion 4 | def f1[T]: List[T] => List[T] = { 5 | case Nil => Nil 6 | case x :: xs => x :: x :: f1(xs) 7 | } 8 | 9 | // Direct tail recursion (inefficient) 10 | @annotation.tailrec 11 | def f2[T](list: List[T], acc: List[T] = Nil): List[T] = list match { 12 | case Nil => acc 13 | case x :: xs => f2(xs, acc ::: List(x, x)) 14 | } 15 | 16 | // Tail recursion with "reverse" 17 | @annotation.tailrec 18 | def f3[T](list: List[T], acc: List[T] = Nil): List[T] = list match { 19 | case Nil => acc.reverse 20 | case x :: xs => f3(xs, x :: x :: acc) 21 | } 22 | 23 | // Right folding 24 | def f4[T](list: List[T]): List[T] = 25 | list.foldRight(Nil: List[T])((x, xs) => x :: x :: xs) 26 | 27 | // Direct left folding (inefficient) 28 | def f5[T](list: List[T]): List[T] = 29 | list.foldLeft(Nil: List[T])((xs, x) => xs ::: List(x, x)) 30 | 31 | // Left folding with reverse 32 | def f6[T](list: List[T]): List[T] = 33 | list.foldLeft(Nil: List[T])((xs, x) => x :: x :: xs).reverse 34 | 35 | // Map then flatten 36 | def f7[T](list: List[T]): List[T] = 37 | list.map(List.fill(2)(_)).flatten 38 | 39 | // Using flatMap 40 | def f8[T](list: List[T]): List[T] = 41 | list.flatMap(List.fill(2)(_)) -------------------------------------------------------------------------------- /java/P02.java: -------------------------------------------------------------------------------- 1 | // P02 Find the last but one element of a list. 2 | 3 | import core.List; 4 | 5 | import java.util.NoSuchElementException; 6 | 7 | import static core.List.*; 8 | 9 | class P02 { 10 | // "Build-in" methods ;) 11 | T f1(List list) { 12 | return list.init().last(); 13 | } 14 | 15 | // Tail-recursive "pattern matching" without pattern matching 16 | T f2(List list) { 17 | if (list.isEmpty()) throw new NoSuchElementException("List is empty"); 18 | List tail = list.tail(); 19 | if (tail.isEmpty()) throw new NoSuchElementException("Singleton list"); 20 | if (tail.tail().isEmpty()) return list.head(); 21 | return f2(tail); 22 | } 23 | 24 | // Imperative approach with two variables 25 | T f3(List list) { 26 | if (list.isEmpty()) throw new NoSuchElementException("List is empty"); 27 | T a = null; 28 | T b = null; 29 | for (T each : list) { 30 | b = a; 31 | a = each; 32 | } 33 | if (b == null) throw new NoSuchElementException("Singleton list"); 34 | return b; 35 | } 36 | 37 | // "Build-in" methods with index 38 | T f4(List list) { 39 | return list.reverse().get(1); 40 | } 41 | } -------------------------------------------------------------------------------- /java/P10.java: -------------------------------------------------------------------------------- 1 | // P10 Run-length encoding of a list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | import static core.Pair.*; 8 | 9 | class P10 { 10 | // Recursion 11 | List> f1(List> list) { 12 | if (list.isEmpty()) { 13 | return nil(); 14 | } else { 15 | List h = list.head(); 16 | return cons(pair(h.length(), h.head()), f1(list.tail())); 17 | } 18 | } 19 | 20 | // Tail recursion 21 | List> f2(List> list) { 22 | return f2_inner(List.>nil(), list); 23 | } 24 | 25 | private List> f2_inner(List> acc, List> list) { 26 | if (list.isEmpty()) { 27 | return acc.reverse(); 28 | } else { 29 | List h = list.head(); 30 | return f2_inner(cons(pair(h.length(), h.head()), acc), list.tail()); 31 | } 32 | } 33 | 34 | // Imperative 35 | List> f3(List> list) { 36 | List> result = nil(); 37 | for (List each : list.reverse()) 38 | result = cons(pair(each.length(), each.head()), result); 39 | return result; 40 | } 41 | } -------------------------------------------------------------------------------- /java/P14.java: -------------------------------------------------------------------------------- 1 | // P14 Duplicate the elements of a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P14 { 8 | // Recursion 9 | List f1(List list) { 10 | return list.isEmpty() 11 | ? List.nil() 12 | : cons(list.head(), cons(list.head(), f1(list.tail()))); 13 | } 14 | 15 | // Direct tail recursion (inefficient) 16 | List f2(List list) { 17 | return f2_inner(List.nil(), list); 18 | } 19 | 20 | private List f2_inner(List acc, List list) { 21 | return list.isEmpty() 22 | ? acc 23 | : f2_inner(concat(acc, replicate(2, list.head())), list.tail()); 24 | } 25 | 26 | // Tail recursion with "reverse" 27 | List f3(List list) { 28 | return f3_inner(List.nil(), list); 29 | } 30 | 31 | private List f3_inner(List acc, List list) { 32 | return list.isEmpty() 33 | ? acc.reverse() 34 | : f3_inner(cons(list.head(), cons(list.head(), acc)), list.tail()); 35 | } 36 | 37 | // Imperative 38 | List f4(List list) { 39 | List acc = nil(); 40 | for (T each : list) acc = cons(each, cons(each, acc)); 41 | return acc.reverse(); 42 | } 43 | } -------------------------------------------------------------------------------- /java/P25.java: -------------------------------------------------------------------------------- 1 | // P25 Generate a random permutation of the elements of a list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import java.util.Random; 7 | 8 | import static core.Pair.*; 9 | import static core.List.*; 10 | 11 | class P25 { 12 | private final Random random = new Random(); 13 | 14 | // The obvious answer is P23.f1(list.length(), list) 15 | // Let's directly select a random permutation for a different implementation 16 | List f1(List list) { 17 | List> all = permutations(list); 18 | return all.get(random.nextInt(all.length())); 19 | } 20 | 21 | private List> permutations(List list) { 22 | if (list.isEmpty()) return singleton(List.nil()); 23 | 24 | List> result = nil(); 25 | 26 | for (int i = 0; i < list.length(); i++) { 27 | Pair, T> p = removeAt(list, i); 28 | 29 | for (List permutation : permutations(p.getA())) { 30 | result = cons(cons(p.getB(), permutation), result); 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | 37 | private Pair, T> removeAt(List list, int n) { 38 | Pair, List> p = list.splitAt(n); 39 | List a = p.getA(); 40 | List b = p.getB(); 41 | return pair(concat(a, b.tail()), b.head()); 42 | } 43 | } -------------------------------------------------------------------------------- /java/P17.java: -------------------------------------------------------------------------------- 1 | // P17 Split a list into two parts; the length of the first part is given. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | import static core.Pair.pair; 8 | 9 | class P17 { 10 | // Using 'predefined' function 11 | Pair, List> f1(int n, List list) { 12 | return list.splitAt(n); 13 | } 14 | 15 | // Using "take" and "drop" 16 | Pair, List> f2(int n, List list) { 17 | return pair(list.take(n), list.drop(n)); 18 | } 19 | 20 | // Recursion with a counter 21 | Pair, List> f3(int n, List list) { 22 | if (list.isEmpty()) 23 | return pair(List.nil(), List.nil()); 24 | 25 | if (n == 0) 26 | return pair(List.nil(), list); 27 | 28 | Pair, List> p = f3(n - 1, list.tail()); 29 | 30 | return pair(cons(list.head(), p.getA()), p.getB()); 31 | } 32 | 33 | // Tail recursion with a counter 34 | Pair, List> f4(int n, List list) { 35 | return f4_inner(List.nil(), n, list); 36 | } 37 | 38 | private Pair, List> f4_inner(List acc, int n, List list) { 39 | return list.isEmpty() 40 | ? pair(acc.reverse(), List.nil()) 41 | : n == 0 ? pair(acc.reverse(), list) : f4_inner(cons(list.head(), acc), n - 1, list.tail()); 42 | } 43 | } -------------------------------------------------------------------------------- /scala/P18.scala: -------------------------------------------------------------------------------- 1 | // P18 Extract a slice from a list. 2 | 3 | // Using "take" and "drop" 4 | def f1[T](list: List[T], i: Int, k: Int): List[T] = 5 | list.take(k).drop(i - 1) 6 | 7 | // Using "splitAt" 8 | def f2[T](list: List[T], i: Int, k: Int): List[T] = 9 | list.splitAt(k)._1.splitAt(i - 1)._2 10 | 11 | // Recursion 12 | def f3[T](list: List[T], i: Int, k: Int): List[T] = { 13 | list match { 14 | case Nil => Nil 15 | case x :: xs => 16 | if (i > 1) 17 | f3(xs, i - 1, k - 1) 18 | else if (k > 0) 19 | x :: f3(xs, 1, k - 1) 20 | else Nil 21 | } 22 | } 23 | 24 | // Tail recursion 25 | @annotation.tailrec 26 | def f4[T](list: List[T], i: Int, k: Int, acc: List[T] = Nil): List[T] = { 27 | list match { 28 | case Nil => acc.reverse 29 | case x :: xs => 30 | if (i > 1) 31 | f4(xs, i - 1, k - 1, acc) 32 | else if (k > 0) 33 | f4(xs, 1, k - 1, x :: acc) 34 | else acc.reverse 35 | } 36 | } 37 | 38 | // Filter by index 39 | def f5[T](list: List[T], i: Int, k: Int): List[T] = 40 | list.zip(1 to k).filter(_._2 >= i).unzip._1 41 | 42 | // Using for comprehension 43 | def f6[T](list: List[T], i: Int, k: Int): List[T] = 44 | for ((x, n) <- list.zip(1 to k) if n >= i) yield x 45 | 46 | // Folding 47 | def f7[T](list: List[T], i: Int, k: Int): List[T] = { 48 | list.zip(1 to k).foldRight(Nil: List[T]) { 49 | case ((x, n), acc) => if (n >= i) x :: acc else acc 50 | } 51 | } -------------------------------------------------------------------------------- /java/P01.java: -------------------------------------------------------------------------------- 1 | // P01 Find the last element of a list. 2 | 3 | import core.List; 4 | import static core.List.*; 5 | 6 | import java.util.NoSuchElementException; 7 | 8 | class P01 { 9 | // "Predefined" function 10 | T f0(List list) { 11 | return list.last(); 12 | } 13 | 14 | // The fastest (but verbose) version 15 | T f1(List list) { 16 | if (list.isEmpty()) throw new NoSuchElementException("List is empty"); 17 | List elements = list.tail(); 18 | List result = list; 19 | while (elements.nonEmpty()) { 20 | result = elements; 21 | elements = elements.tail(); 22 | } 23 | return result.head(); 24 | } 25 | 26 | // Instantiates an iterator to enumerate elements (CPU and GC overhead) 27 | T f2(List list) { 28 | if (list.isEmpty()) throw new NoSuchElementException("List is empty"); 29 | T result = null; 30 | for (T each : list) 31 | result = each; 32 | return result; 33 | } 34 | 35 | // Uses (tail) recursion (can produce stack overflow errors in Java) 36 | T f3(List list) { 37 | if (list.isEmpty()) throw new NoSuchElementException("List is empty"); 38 | return f3_inner(list); 39 | } 40 | 41 | private T f3_inner(List list) { 42 | List tail = list.tail(); 43 | return tail.isEmpty() ? list.head() : f3(tail); 44 | } 45 | } -------------------------------------------------------------------------------- /java/P23.java: -------------------------------------------------------------------------------- 1 | // P23 Extract a given number of randomly selected elements from a list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import java.util.Random; 7 | 8 | import static core.List.*; 9 | import static core.Pair.pair; 10 | 11 | class P23 { 12 | private final Random random = new Random(); 13 | 14 | // Building a target list while removing items from the source (recursively) 15 | // Time complexity is O(n^2) in worst and average cases, O(n) - in best case 16 | List f1(int n, List list) { 17 | if (n > 0) { 18 | int i = random.nextInt(list.length()); 19 | Pair, T> p = removeAt(list, i); 20 | return cons(p.getB(), f1(n - 1, p.getA())); 21 | } else { 22 | return nil(); 23 | } 24 | } 25 | 26 | // Imperative, time complexity is the same as above 27 | List f2(int n, List list) { 28 | List acc = nil(); 29 | while (n > 0) { 30 | int i = random.nextInt(list.length()); 31 | Pair, T> p = removeAt(list, i); 32 | acc = cons(p.getB(), acc); 33 | list = p.getA(); 34 | n--; 35 | } 36 | return acc; 37 | } 38 | 39 | // Helper function 40 | private Pair, T> removeAt(List list, int n) { 41 | Pair, List> p = list.splitAt(n); 42 | List a = p.getA(); 43 | List b = p.getB(); 44 | return pair(concat(a, b.tail()), b.head()); 45 | } 46 | } -------------------------------------------------------------------------------- /java/P21.java: -------------------------------------------------------------------------------- 1 | // P21 Insert an element at a given position into a list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | 8 | class P21 { 9 | // Using "splitAt" 10 | List f1(List list, int n, T x) { 11 | Pair, List> p = list.splitAt(n - 1); 12 | List a = p.getA(); 13 | List b = p.getB(); 14 | return concat(a, cons(x, b)); 15 | } 16 | 17 | // By index (inefficient) 18 | List f2(List list, int n, T x) { 19 | return concat(list.take(n - 1), cons(x, list.drop(n - 1))); 20 | } 21 | 22 | // Recursion 23 | List f3(List list, int n, T x) { 24 | return n == 1 ? cons(x, list) : cons(list.head(), f2(list.tail(), n - 1, x)); 25 | } 26 | 27 | // Tail recursion 28 | List f4(List list, int n, T x) { 29 | return f4_inner(list, n, x, List.nil()); 30 | } 31 | 32 | private List f4_inner(List list, int n, T x, List acc) { 33 | return n == 1 34 | ? concat(acc.reverse(), cons(x, list)) 35 | : f4_inner(list.tail(), n - 1, x, cons(list.head(), acc)); 36 | } 37 | 38 | // Imperative 39 | List f5(List list, int n, T x) { 40 | List result = nil(); 41 | int i = 0; 42 | for (T each : list) { 43 | i++; 44 | result = i == 1 ? cons(x, cons(each, result)) : cons(each, result); 45 | } 46 | return result.reverse(); 47 | } 48 | } -------------------------------------------------------------------------------- /java/P16.java: -------------------------------------------------------------------------------- 1 | // P16 Drop every N'th element from a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.*; 6 | 7 | class P16 { 8 | // Recursion with a counter 9 | List f1(int n, List list) { 10 | return f1_inner(n, n, list); 11 | } 12 | 13 | private List f1_inner(int n, int k, List list) { 14 | return list.isEmpty() ? List.nil() : k == 1 15 | ? f1_inner(n, n, list.tail()) 16 | : cons(list.head(), f1_inner(n, k - 1, list.tail())); 17 | } 18 | 19 | // Tail recursion 20 | List f2(int n, List list) { 21 | return f2_inner(n, n, List.nil(), list); 22 | } 23 | 24 | private List f2_inner(int n, int k, List acc, List list) { 25 | return list.isEmpty() ? acc.reverse() : k == 1 26 | ? f2_inner(n, n, acc, list.tail()) 27 | : f2_inner(n, k - 1, cons(list.head(), acc), list.tail()); 28 | } 29 | 30 | // Recursion with "take" and "drop" 31 | List f3(int n, List list) { 32 | return list.isEmpty() 33 | ? List.nil() 34 | : concat(list.take(n - 1), f3(n, list.drop(n))); 35 | } 36 | 37 | // Imperative 38 | List f4(int n, List list) { 39 | List acc = nil(); 40 | int k = 1; 41 | for (T it : list) { 42 | if (k < n) { 43 | acc = cons(it, acc); 44 | k++; 45 | } else { 46 | k = 1; 47 | } 48 | } 49 | return acc.reverse(); 50 | } 51 | } -------------------------------------------------------------------------------- /scala/P13.scala: -------------------------------------------------------------------------------- 1 | // P13 Run-length encoding of a list (direct solution). 2 | 3 | // Values factory 4 | def makeValue[T](n: Int, x: T): Any = 5 | if (n == 1) x else (n, x) 6 | 7 | // A simple solution, but there's still some kind of sublists 8 | def f1: List[Any] => List[Any] = { 9 | case Nil => Nil 10 | case x :: xs => 11 | val (a, b) = xs.span(x ==) 12 | makeValue(a.length + 1, x) :: f1(b) 13 | } 14 | 15 | // Recursion, "look-behind" 16 | def f2: List[Any] => List[Any] = { 17 | case Nil => Nil 18 | case x :: xs => toValues(1, x, xs) 19 | } 20 | 21 | def toValues(n: Int, x: Any, l: List[Any]): List[Any] = l match { 22 | case Nil => List(makeValue(n, x)) 23 | case y :: ys => if (y == x) toValues(n + 1, y, ys) else makeValue(n, x) :: toValues(1, y, ys) 24 | } 25 | 26 | // With custom data 27 | abstract sealed class Entry[T] 28 | case class Value[T](v: T) extends Entry[T] 29 | case class Sequence[T](n: Int, v: T) extends Entry[T] 30 | 31 | // Entries factory 32 | def makeEntry[T](n: Int, x: T): Entry[T] = 33 | if (n == 1) Value(x) else Sequence(n, x) 34 | 35 | // Using "span" 36 | def f3[T]: List[T] => List[Entry[T]] = { 37 | case Nil => Nil 38 | case x :: xs => 39 | val (a, b) = xs.span(x ==) 40 | makeEntry(a.length + 1, x) :: f3(b) 41 | } 42 | 43 | // Direct method using custom data 44 | def f4[T]: List[T] => List[Entry[T]] = { 45 | case Nil => Nil 46 | case x :: xs => toEntries(1, x, xs) 47 | } 48 | 49 | def toEntries[T](n: Int, x: T, l: List[T]): List[Entry[T]] = l match { 50 | case Nil => List(makeEntry(n, x)) 51 | case y :: ys => if (y == x) toEntries(n + 1, y, ys) else makeEntry(n, x) :: toEntries(1, y, ys) 52 | } -------------------------------------------------------------------------------- /scala/P16.scala: -------------------------------------------------------------------------------- 1 | // P16 Drop every N'th element from a list. 2 | 3 | // Recursion 4 | def f1[T](n: Int, list: List[T]): List[T] = { 5 | def f[T]: (Int, List[T]) => List[T] = { 6 | case (_, Nil) => Nil 7 | case (1, _ :: xs) => f(n, xs) 8 | case (k, x :: xs) => x :: f(k - 1, xs) 9 | } 10 | f(n, list) 11 | } 12 | 13 | // Tail recursion 14 | def f2[T](n: Int, list: List[T]): List[T] = { 15 | @annotation.tailrec 16 | def f[T](k: Int, acc: List[T], l: List[T]): List[T] = (k, l) match { 17 | case (_, Nil) => acc.reverse 18 | case (1, _ :: xs) => f(n, acc, xs) 19 | case (k, x :: xs) => f(k - 1, x :: acc, xs) 20 | } 21 | f(n, Nil, list) 22 | } 23 | 24 | // Recursion with "take" and "drop" 25 | def f3[T](n: Int, list: List[T]): List[T] = 26 | if (list.nonEmpty) list.take(n - 1) ::: f3(n, list.drop(n)) else Nil 27 | 28 | // Zip with cycle, filter, map 29 | def f4[T](n: Int, list: List[T]): List[T] = { 30 | val cycle = Stream.iterate(1)(it => if (it < n) it + 1 else 1) 31 | list.zip(cycle).filter(_._2 < n).map(_._1) 32 | } 33 | 34 | // Using "for comprehensions" 35 | def f5[T](n: Int, list: List[T]): List[T] = { 36 | val cycle = Stream.iterate(1)(it => if (it < n) it + 1 else 1) 37 | for((x, k) <- list.zip(cycle) if k < n) yield x 38 | } 39 | 40 | // ZipWithIndex and modulo 41 | def f6[T](n: Int, list: List[T]): List[T] = 42 | list.zipWithIndex.filter(it => (it._2 + 1) % n > 0).map(_._1) 43 | 44 | // Imperative 45 | def f7[T](n: Int, list: List[T]): List[T] = { 46 | var acc: List[T] = Nil 47 | var k = 1 48 | for (it <- list) { 49 | if (k < n) { 50 | acc ::= it 51 | k += 1 52 | } else { 53 | k = 1 54 | } 55 | } 56 | acc.reverse 57 | } -------------------------------------------------------------------------------- /java/P20.java: -------------------------------------------------------------------------------- 1 | // P20 Remove the K'th element from a list. 2 | 3 | import core.List; 4 | import core.Pair; 5 | 6 | import static core.List.*; 7 | import static core.Pair.pair; 8 | 9 | class P20 { 10 | // Using "splitAt" 11 | Pair, T> f1(List list, int n) { 12 | Pair, List> p = list.splitAt(n - 1); 13 | List a = p.getA(); 14 | List b = p.getB(); 15 | return pair(concat(a, b.tail()), b.head()); 16 | } 17 | 18 | // By index (inefficient) 19 | Pair, T> f2(List list, int n) { 20 | return pair(concat(list.take(n - 1), list.drop(n)), list.get(n - 1)); 21 | } 22 | 23 | // Recursion 24 | Pair, T> f3(List list, int n) { 25 | T h = list.head(); 26 | List t = list.tail(); 27 | if (n > 1) { 28 | Pair, T> p = f3(t, n - 1); 29 | return pair(cons(h, p.getA()), p.getB()); 30 | } else { 31 | return pair(t, h); 32 | } 33 | } 34 | 35 | // Tail recursion 36 | Pair, T> f4(List list, int n) { 37 | return f4_inner(list, n, List.nil()); 38 | } 39 | 40 | private Pair, T> f4_inner(List list, int n, List acc) { 41 | T h = list.head(); 42 | List t = list.tail(); 43 | if (n > 1) { 44 | return f4_inner(t, n - 1, cons(h, acc)); 45 | } else { 46 | return pair(concat(acc.reverse(), t), h); 47 | } 48 | } 49 | 50 | // Imperative 51 | Pair, T> f5(List list, int n) { 52 | List xs = nil(); 53 | T x = null; 54 | int i = 0; 55 | for (T each : list) { 56 | i++; 57 | if (i == n) 58 | x = each; 59 | else 60 | xs = cons(each, xs); 61 | } 62 | return pair(xs.reverse(), x); 63 | } 64 | } -------------------------------------------------------------------------------- /java/P18.java: -------------------------------------------------------------------------------- 1 | // P18 Extract a slice from a list. 2 | 3 | import core.List; 4 | 5 | import static core.List.cons; 6 | import static core.List.listOfChars; 7 | import static core.List.nil; 8 | 9 | class P18 { 10 | // Using "take" and "drop" 11 | List f1(List list, int i, int k) { 12 | return list.take(k).drop(i - 1); 13 | } 14 | 15 | // Using "splitAt" 16 | List f2(List list, int i, int k) { 17 | return list.splitAt(k).getA().splitAt(i - 1).getB(); 18 | } 19 | 20 | // Recursion 21 | List f3(List list, int i, int k) { 22 | if (list.isEmpty()) { 23 | return nil(); 24 | } else { 25 | if (i > 1) { 26 | return f3(list.tail(), i - 1, k - 1); 27 | } else { 28 | if (k > 0) { 29 | return cons(list.head(), f3(list.tail(), 1, k - 1)); 30 | } else { 31 | return nil(); 32 | } 33 | } 34 | } 35 | } 36 | 37 | // Tail recursion 38 | List f4(List list, int i, int k) { 39 | return f4_inner(list, i, k, List.nil()).reverse(); 40 | } 41 | 42 | private List f4_inner(List list, int i, int k, List acc) { 43 | if (list.isEmpty()) { 44 | return acc; 45 | } else { 46 | if (i > 1) { 47 | return f4_inner(list.tail(), i - 1, k - 1, acc); 48 | } else { 49 | if (k > 0) { 50 | return f4_inner(list.tail(), 1, k - 1, cons(list.head(), acc)); 51 | } else { 52 | return acc; 53 | } 54 | } 55 | } 56 | } 57 | 58 | // Filter by index (imperative style) 59 | List f5(List list, int i, int k) { 60 | int n = 1; 61 | List result = nil(); 62 | for (T each : list) { 63 | if (n > k) break; 64 | if (n >= i) result = cons(each, result); 65 | n++; 66 | } 67 | return result.reverse(); 68 | } 69 | } -------------------------------------------------------------------------------- /java/core/List.java: -------------------------------------------------------------------------------- 1 | package core; 2 | 3 | import java.util.Arrays; 4 | import java.util.Iterator; 5 | import java.util.NoSuchElementException; 6 | 7 | // A Scala-like immutable List implementation in Java (without higher-order function) 8 | // The performance is not considered in favor of cleaner code (for demo purposes) 9 | public class List implements Iterable { 10 | private static final List NIL = new EmptyList(); 11 | 12 | private final T _head; 13 | 14 | private final List _tail; 15 | 16 | 17 | private List(T head, List tail) { 18 | _head = head; 19 | _tail = tail; 20 | } 21 | 22 | public T head() { 23 | return _head; 24 | } 25 | 26 | public List tail() { 27 | return _tail; 28 | } 29 | 30 | public boolean isEmpty() { 31 | return false; 32 | } 33 | 34 | public boolean nonEmpty() { 35 | return !isEmpty(); 36 | } 37 | 38 | @Override 39 | public Iterator iterator() { 40 | return new ListIterator(this); 41 | } 42 | 43 | @SuppressWarnings("unchecked") 44 | public static List nil() { 45 | return NIL; 46 | } 47 | 48 | public static List listOfChars(String chars) { 49 | List list = nil(); 50 | for (Character each : chars.toCharArray()) 51 | list = cons(each, list); 52 | return list.reverse(); 53 | } 54 | 55 | public static List list(T... elements) { 56 | return list(Arrays.asList(elements)); 57 | } 58 | 59 | public static List list(Iterable elements) { 60 | List list = nil(); 61 | for (T each : elements) 62 | list = cons(each, list); 63 | return list.reverse(); 64 | } 65 | 66 | public static List singleton(T element) { 67 | return new List(element, List.nil()); 68 | } 69 | 70 | public static List replicate(int n, T element) { 71 | List list = nil(); 72 | for (int i = 0; i < n; i++) 73 | list = cons(element, list); 74 | return list; 75 | } 76 | 77 | public static List range(int a, int b) { 78 | if (a > b) { 79 | return nil(); 80 | } else { 81 | return cons(a, range(a + 1, b)); 82 | } 83 | } 84 | 85 | public static List cons(T head, List tail) { 86 | return new List(head, tail); 87 | } 88 | 89 | public static List concat(List prefix, List suffix) { 90 | List result = suffix; 91 | for (T each : prefix.reverse()) 92 | result = cons(each, result); 93 | return result; 94 | } 95 | 96 | public List prepend(T head) { 97 | return cons(head, this); 98 | } 99 | 100 | public List prepend(List prefix) { 101 | return concat(prefix, this); 102 | } 103 | 104 | public List append(List suffix) { 105 | return concat(this, suffix); 106 | } 107 | 108 | public List reverse() { 109 | List list = nil(); 110 | for (T each : this) 111 | list = cons(each, list); 112 | return list; 113 | } 114 | 115 | public int length() { 116 | int c = 0; 117 | for (T each : this) 118 | c++; 119 | return c; 120 | } 121 | 122 | public T get(int i) { 123 | int c = 0; 124 | for (T each : this) 125 | if (c == i) 126 | return each; 127 | else 128 | c++; 129 | throw new IndexOutOfBoundsException(); 130 | } 131 | 132 | public T last() { 133 | if (isEmpty()) throw new NoSuchElementException("List is empty"); 134 | T result = null; 135 | for (T each : this) 136 | result = each; 137 | return result; 138 | } 139 | 140 | public List take(int i) { 141 | return take(i, this).reverse(); 142 | } 143 | 144 | public List takeRight(int i) { 145 | return take(i, this.reverse()); 146 | } 147 | 148 | private static List take(int i, List list) { 149 | List result = nil(); 150 | int c = 0; 151 | for (T each : list) { 152 | if (c == i) break; 153 | result = cons(each, result); 154 | c++; 155 | } 156 | return result; 157 | } 158 | 159 | public List drop(int i) { 160 | return drop(i, this).reverse(); 161 | } 162 | 163 | public List dropRight(int i) { 164 | return drop(i, this.reverse()); 165 | } 166 | 167 | private static List drop(int i, List list) { 168 | List result = nil(); 169 | int c = i; 170 | for (T each : list) { 171 | c--; 172 | if (c >= 0) continue; 173 | result = cons(each, result); 174 | } 175 | return result; 176 | } 177 | 178 | public List init() { 179 | if (isEmpty()) throw new UnsupportedOperationException("List is empty"); 180 | return dropRight(1); 181 | } 182 | 183 | public Pair, List> splitAt(int index) { 184 | return Pair.pair(take(index), drop(index)); 185 | } 186 | 187 | @Override 188 | public boolean equals(Object obj) { 189 | if (!(obj instanceof List)) return false; 190 | 191 | Iterator ours = this.iterator(); 192 | Iterator theirs = ((List) obj).iterator(); 193 | 194 | while (ours.hasNext() && theirs.hasNext()) 195 | if (!ours.next().equals(theirs.next())) 196 | return false; 197 | 198 | return !ours.hasNext() && !theirs.hasNext(); 199 | } 200 | 201 | @Override 202 | public String toString() { 203 | StringBuilder builder = new StringBuilder(); 204 | builder.append('['); 205 | Iterator it = iterator(); 206 | while (it.hasNext()) { 207 | builder.append(it.next()); 208 | if (it.hasNext()) builder.append(", "); 209 | } 210 | builder.append(']'); 211 | return builder.toString(); 212 | } 213 | 214 | 215 | private static class EmptyList extends List { 216 | public EmptyList() { 217 | super(null, null); 218 | } 219 | 220 | @Override 221 | public Object head() { 222 | throw new IllegalStateException("Accessing head of the an empty list"); 223 | } 224 | 225 | @Override 226 | public List tail() { 227 | throw new IllegalStateException("Accessing tail of the an empty list"); 228 | } 229 | 230 | @Override 231 | public boolean isEmpty() { 232 | return true; 233 | } 234 | } 235 | 236 | private class ListIterator implements Iterator { 237 | private List _list; 238 | 239 | public ListIterator(List list) { 240 | _list = list; 241 | } 242 | 243 | @Override 244 | public boolean hasNext() { 245 | return !_list.isEmpty(); 246 | } 247 | 248 | @Override 249 | public T next() { 250 | T value = _list.head(); 251 | _list = _list.tail(); 252 | return value; 253 | } 254 | 255 | @Override 256 | public void remove() { 257 | throw new UnsupportedOperationException(); 258 | } 259 | } 260 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------