Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Last active December 18, 2017 04:24
Show Gist options
  • Save arialdomartini/942cec4c5d8055a50287507f89db607c to your computer and use it in GitHub Desktop.
Save arialdomartini/942cec4c5d8055a50287507f89db607c to your computer and use it in GitHub Desktop.
Patternmatching.scala
def flatten(ls: List[_]): List[Int] = ls match {
case Nil => Nil
case (a: Int) :: tail => a :: flatten(tail)
case (a: List[_]) :: tail => flatten(a) ::: flatten(tail)
case _ :: tail => flatten(tail)
}
// oppure adforittura
def flattenRecur(ls: List[Any]): List[Int] = ls match {
case (head: Int) :: (tail: List[Any]) => head :: flattenRecur(tail)
case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail)
case (head: List[Any]) :: (tail: List[Any]) => flattenRecur(head) :: flattenRecur(tail) // non-variable type... on this line.
}
Opure in haskell
:: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment