Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Pattern Matching
- def multAllPM(m: Int, List: List[Int]): List[Int] = list match {
- case Nil => Nil
- case head :: tail => m*head :: multAll(m, tail)
- }
- def multAll(m: Int, list: List[Int]): List[Int] = {
- if(list == Nil) return Nil
- else return m*list.head :: multAll(m, list.tail)
- }
- test("multAll", multAll _, "m", "list")
- =====
- Some stuff pattern matching can do that if can't: what if we left out the base case by accident, the compiler would tell us that we forgot the empty case
- Or what if there was a typo
- =====
- Nested Patterns:
- def everyOther(list: List[Int]): List[Int] = list match {
- case x :: _ :: rest => x :: everyOther(rest)
- case _ => list
- }
- =====
- Types of patterns:
- _ matches anything
- x matches anything but can refer to it as x
- 0,1,"hello",true matches when it's exactly what the hardcoded value is
- Nil,None,Empty will only match that thing but it's for empty shit
- def fact(n: Int): Int = n match {
- case 0 => 1
- case _ => n*fact(n-1)
- }
- complex patterns-- (x,y,z) (Nil, "hello", 4)
- x :: xs
- you can also use pattern matching in other stuff?
- val (x,y,z) = tup
- instead of val x = tup._1 etc
- val Some(x) = opt
- val y :: ys = list
- Some is an Option (can also be None)
- var len = 0
- for (_ <- list) {
- len += 1
- }
- for (opt <- list) {
- if (opt != None)
- println(opt.get)
- }
- sealed trait tree
- case object Empty extends Tree
- case class Node(left: Tree, item: Int, right: Tree) extends Tree
- def size(tree: Tree): Int = tree match {
- case Empty => 0
- case Node(left,item,right)
- }
- =====
- def lookup(tree: Tree, find: Int): Boolean = tree match {
- case Empty => false
- case (left, item, right) => {
- if(item == find) true
- else if(item < find) lookup(left)
- else lookup(right)
- }
- }
- =====
- =====
- More Pattern Matching
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement