Last active
August 29, 2015 14:16
-
-
Save tolitius/d543844495621ebf048c to your computer and use it in GitHub Desktop.
scala / clojure: pattern matching with rest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def 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