Skip to content

Instantly share code, notes, and snippets.

@tolitius
Last active August 29, 2015 14:16
Show Gist options
  • Save tolitius/d543844495621ebf048c to your computer and use it in GitHub Desktop.
Save tolitius/d543844495621ebf048c to your computer and use it in GitHub Desktop.
scala / clojure: pattern matching with rest
repl> (let [[a b] [1 41 3 4 5 6 7 8]]
(+ a b))
42
;; anywhere, function params? sure!
(defn sum [[a b]] ;; define a function (inner brackets fetch first two elements)
(+ a b))
(sum [1 41 3 4 5 6 7 8 9]) ;; use it
42
def withRest ( s: Any ) = s match {
case Seq( a, b, _ * ) => ( a, b )
case _ => println( "kaBoom!" )
}
withRest( Seq( 1, 2, 3, 4, 5, 6, 7, 8 ) ) shouldBe ( 1, 2 )
//OR simpler
val Seq( a, b, _ * ) = Seq( 1, 2, 3, 4, 5, 6, 7, 8 )
a shouldBe 1
b shouldBe 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment