Skip to content

Instantly share code, notes, and snippets.

@t1anchen
Last active December 27, 2015 01:59
Show Gist options
  • Save t1anchen/7249422 to your computer and use it in GitHub Desktop.
Save t1anchen/7249422 to your computer and use it in GitHub Desktop.
maplist
;; Leiningen 2.3.2
;; Clojure 1.5.1
;; REPL
;;
(defn maplist [f coll] (map #(apply f %) (take (count coll) (iterate rest coll))))
(maplist min (range 10))
;; (0 1 2 3 4 5 6 7 8 9)
(maplist max (range 10))
;; (9 9 9 9 9 9 9 9 9 9)
(maplist * (range 1 11))
;; (3628800 3628800 1814400 604800 151200 30240 5040 720 90 10)
(maplist + (range 1 11))
;; (55 54 52 49 45 40 34 27 19 10)
// sbt 0.12
// scala 2.10.2
// console mode
//
val lst = 1 to 10 toList
// warning: there were 1 feature warning(s); re-run with -feature for details
// lst: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
lst.scanRight(1)(_ * _)
// res0: List[Int] = List(3628800, 3628800, 1814400, 604800, 151200, 30240, 5040, 720, 90, 10, 1)
lst.scanRight(0)(_ + _)
// res1: List[Int] = List(55, 54, 52, 49, 45, 40, 34, 27, 19, 10, 0)
// no min/max for scanRight because scan(Left|Right) needs an Identity Element (http://en.wikipedia.org/wiki/Identity_element)
// UPDATE on 2013-11-05
lst.tails.toList
// res24: List[List[Int]] = List(List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), List(2, 3, 4, 5, 6, 7, 8, 9, 10), List(3, 4, 5, 6, 7, 8, 9, 10), List(4, 5, 6, 7, 8, 9, 10), List(5, 6, 7, 8, 9, 10), List(6, 7, 8, 9, 10), List(7, 8, 9, 10), List(8, 9, 10), List(9, 10), List(10), List()) <- Empty List is here!
lst.tails.toList.filter(_.size>0)
// res25: List[List[Int]] = List(List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), List(2, 3, 4, 5, 6, 7, 8, 9, 10), List(3, 4, 5, 6, 7, 8, 9, 10), List(4, 5, 6, 7, 8, 9, 10), List(5, 6, 7, 8, 9, 10), List(6, 7, 8, 9, 10), List(7, 8, 9, 10), List(8, 9, 10), List(9, 10), List(10)) <- Empty List is not here!
(require 'cl)
(maplist #'(lambda (x) (apply #'* x)) (loop for i from 1 to 10 collect i))
;; (3628800 3628800 1814400 604800 151200 30240 5040 720 90 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment