Last active
November 10, 2020 03:02
-
-
Save rupeshtr78/4fe3c3c003fe70d057f03442f72e6673 to your computer and use it in GitHub Desktop.
ListPatternMatching
This file contains 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 listPatternMatching[T](someList: List[T]): String = { | |
someList match { | |
case Nil => s"empty list" | |
case x :: Nil => s"list with only one element" | |
case List(x) => s"list with only one element" | |
case x :: xs => s"a list with at least one element. $x is the head xs to the tail," // xs could be Nil or some other list. | |
case 1 :: 2 :: cs => s"lists that starts with 1 and then 2" | |
case (x, y) :: ps => s"a list where the head element is a pair" | |
case _ => s"default case if none of the above matches" | |
} | |
val pairs: List[(Char, Int)] = ('a', 2) :: ('b', 3) :: Nil | |
val chars: List[Char] = pairs map { | |
case (ch, num) => ch | |
} | |
def aFilter[A](list: AList[A], f: A => Boolean): AList[A] = { | |
def loop (l:AList[A],result:AList[A]) :AList[A] = l match { | |
case Nil => reverse(result) | |
case Cons(head, tail) if(!f(head)) => loop(tail,Cons(head,result)) | |
case Cons(head, tail) if(f(head)) =>{ | |
// println("Second " + l,result) | |
loop(drop(l,1),result) | |
} | |
} | |
loop(list,Nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment