How to split a List to tuples? - list
I am trying to define a function, that would take a list and split it down n without using take, drop or grouped
def mySplit[X](n: Int, xs: List[X]): (List[X], List[X]) = {
if (n <= 0) (Nil, xs)
else
if (n >= xs.size) (xs, Nil)
else
if (n < xs.tail.size) (xs.head :: mySplit(n, xs.tail), Nil)
else (Nil, xs.head :: mySplit(n, xs.tail))
}
Here is what I am thinking. If n < xs.tail.size we can build up tuple 1 (representing part 1), else we can work on tuple 2 (second part of the list).
The above does not work. It seems that it does not like the :: when I am constructing part of a tuple.
Am I approaching this the right way?
Example: mySplit(3, (1 to 5).toList) should return (List(1,2,3), List(4,5))
Here is my take, rewritten from scratch:
def mySplit[X](n: Int, xs: List[X]): (List[X], List[X]) = {
xs match {
case Nil => (Nil, Nil)
case head :: tail =>
if(n == 0)
(Nil, xs)
else
mySplit(n - 1, tail) match {
case (before, after) =>
(head :: before, after)
}
}
}
Or alternatively and shorter:
def mySplit[X](n: Int, xs: List[X]): (List[X], List[X]) = {
n match {
case 0 => (Nil, xs)
case s =>
mySplit(s - 1, xs.tail) match {
case (before, after) =>
(xs.head :: before, after)
}
}
}
If you still want to split large lists, here is a tail recursive variant. Its also faster:
import scala.annotation.tailrec
def mySplit[X](n: Int, xs: List[X]): (List[X], List[X]) = {
require(n >= 0)
if (n > 0) {
var result: (List[X], List[X]) = null
#tailrec
def mySplit0(n: Int, l: List[X], r: List[X]): Unit = r match {
case h :: t if (n > 0) => mySplit0(n - 1, h :: l, t)
case _ => result = (l.reverse, r)
}
mySplit0(n, Nil, xs)
result
} else (Nil, xs)
}
Related
Scala: slice a list from the first non-zero element
Suppose I have a list filled with zeroes val a = List(0,0,0,0,2,4,0,6,0,7) I want to slice away the zeroes preceding the first non-zero element and also return the index where the 1st non-zero element is present. Foe the above case I want an output: output = List(2,4,0,6,0,7) idx = 4 How do I do it?
First, you can use zipWithIndex to conveniently pair each element with its index. Then use dropWhile to return all of the preceding zero elements. From there, you'll have all of the remaining elements paired with their indices from the original List. You can unzip them. Since this may result in an empty list, the index you're looking for should be optional. scala> val (remaining, indices) = a.zipWithIndex.dropWhile { case (a, i) => a == 0 }.unzip remaining: List[Int] = List(2, 4, 0, 6, 0, 7) // <--- The list you want indices: List[Int] = List(4, 5, 6, 7, 8, 9) scala> val index = indices.headOption index: Option[Int] = Some(4) // <--- the index of the first non-zero element
This is a use-case for span: val a = List(0,0,0,0,2,4,0,6,0,7) val (zeros, output) = a.span(_ == 0) val idx = zeros.length
use dropWhile: val output = a.dropWhile{ _ == 0 } val idx = output.headOption .map(_ => a.length - output.length) .getOrElse(-1) // index starting from 0, -1 if not found
Sightly modified from #bottaio answer, but returning an Option[Int] instead of a plain Int for the index. def firstNonZero(l: List[Int]): (Option[Int], List[Int]) = { #annotation.tailrec def go(remaining: List[Int], idx: Int): (Int, List[Int]) = remaining match { case Nil => idx -> Nil case 0 :: xs => go(remaining = xs, idx + 1) case xs => idx -> xs } l match { case 0 :: xs => val (idx, list) = go(remaining = xs, idx = 1) Some(idx) -> list case list => None -> list } }
Just another solution using foldLeft: val (i, l) = a.foldLeft((None: Option[Int], List.empty: List[Int]))((b, n) => { if (n == 0 && b._2.isEmpty) (b._1.orElse(Some(0)).map(_ + 1), List.empty) else (b._1.orElse(Some(0)), b._2 :+ n) }) i: Option[Int] = Some(4) l: List[Int] = List(2, 4, 0, 6, 0, 7)
You can do it pretty clean with indexWhere: val idx = a.indexWhere(_!=0) val output = a.drop(idx)
Others have provided answers that requires multiple list traversals. You can write a recursive function to calculate that in a single pass: def firstNonZero(l: List[Int]): (Int, List[Int]) = { #tailrec def go(l: List[Int], idx: Int): (Int, List[Int]) = l match { case Nil => (idx, Nil) case 0 :: xs => go(xs, idx + 1) case xs => (idx, xs) } go(l, 0) } what is also equivalent to val (leadingZeros, rest) = a.span(_ == 0) val (index, output) = (leadingZeros.length, rest)
Scala: List Operations
In Scala, define the function slice(from, until, xs) that selects an interval of elements from the (string) list xs such that for each element x in the interval the following invariant holds: from <= indexOf(x) < until. from: the lowest index to include from this list. until: the highest index to exclude from this list. returns: a list containing the elements greater than or equal to index from extending up to (but not including) index until of this list. example: def test { expect (Cons("b", Cons("c", Nil()))) { slice(1, 3, Cons("a", Cons("b", Cons("c", Cons("d", Cons("e", Nil())))))) } } another example: def test { expect (Cons("d", Cons("e", Nil()))) { slice(3, 7, Cons("a", Cons("b", Cons("c", Cons("d", Cons("e", Nil())))))) } } and this is what I have, but its not that correct. Can someone help me with it? abstract class StringList case class Nil() extends StringList case class Cons(h: String, t: StringList) extends StringList object Solution { // define function slice def slice(from : Int, until : Int, xs : StringList) : StringList = (from, until, xs) match { case (_,_,Nil()) => Nil() case (n, m, _) if(n == m) => Nil() case (n, m, _) if(n > m) => Nil() case (n, m, _) if(n < 0) => Nil() case (n, m, xs) if(n == 0)=> Cons(head(xs), slice(n+1,m,tail(xs))) case (n, m, xs) => { //Cons(head(xs), slice(n+1,m,tail(xs))) if(n == from) { print("\n") print("n == m " + Cons(head(xs), slice(n+1,m,tail(xs)))) print("\n") Cons(head(xs), slice(n+1,m,tail(xs))) } else slice(n+1,m,tail(xs)) } } def head(t : StringList) : String = t match { case Nil() => throw new NoSuchElementException case Cons(h, t) => h } def tail(t : StringList) : StringList = t match { case Nil() => Nil() case Cons(h, t) => t } /* def drop(n : Int, t : StringList) : StringList = (n, t) match { case (0, t) => t case (_, Nil()) => Nil() case (n, t) => drop(n-1 , tail(t)) }*/ }//
This works add a method to find the element at given index : trait StringList case class Nil() extends StringList case class Cons(h: String, t: StringList) extends StringList object Solution { def numberOfElements(str: StringList, count: Int = 0): Int = { if (str == Nil()) count else numberOfElements(tail(str), count + 1) } def elemAtIndex(n: Int, str: StringList, count: Int = 0): String = { if (str == Nil() || n == count) head(str) else elemAtIndex(n, tail(str), count + 1) } def head(str: StringList): String = str match { case Nil() => throw new NoSuchElementException case Cons(h, t) => h } def tail(str: StringList): StringList = str match { case Nil() => Nil() case Cons(h, t) => t } // define function slice def slice(from: Int, until: Int, xs: StringList): StringList = (from, until, xs) match { case (n, m: Int, _) if n == m || n > m || n < 0 => Nil() case (n, m: Int, xs: StringList) => if (m > numberOfElements(xs)) { slice(n, numberOfElements(xs), xs) } else { Cons(elemAtIndex(n, xs), slice(n + 1, m, xs)) } } } scala> Solution.slice(1, 3, Cons("a", Cons("b", Cons("c", Cons("d", Cons("e", Nil())))))) res0: StringList = Cons(b,Cons(c,Nil())) scala> Solution.slice(3, 7, Cons("a", Cons("b", Cons("c", Cons("d", Cons("e", Nil())))))) res0: StringList = Cons(d,Cons(e,Nil()))
Method that add and remove an element from a List
i'm writing a method that take a list: List[(String, Int)] , x:(String, Int) and a n: Int parameters and return a List[(String, Int)] The list parameter represents the input list, the x element represents the element to add to the list, the n represents the maximum dimension of the list. The method has the following behavior: First of all check if the list has n elements. If list has less than n elements, the method add the x elements to the list. Otherwise if the list contain an elements less than x, the method remove the minimum element from the list, and add the x element to the list. I've implemented the method as the following: def method(list: List[(String, Int)], x: (String, Int), n: Int) = { if(list.size < n) list :+ x else { var index = -1 var min = 10000000//some big number for(el <- 0 to list.size) { if(list(el)._2 < x._2 && list(el)._2 < min) { min = list(el)._2 index = el } } if(index != -1) { val newList = list.drop(index) newList :+ x } else list } } Exist a way to express this behavior in a more clean way??
First, a corrected version of what you posted (but it appears, not what you intended) def method(list: List[(String, Int)], x: (String, Int), n: Int) = { if(list.size < n) list :+ x else { var index = -1 for(i <- 0 until list.size) { val el = list(i) if(el._2 < x._2) index = i } if(index != -1) { val (before, after) = list.splitAt(index) val newList = before ++ after.tail newList :+ x } else list } } And some tests val l1 = List(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : List[(String, Int)] = List((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : List[(String, Int)] = List((one,1), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : List[(String, Int)] = List((one,1), (three,3)) Neater version (but still not meeting the spec as mentioned in a comment from the OP) def method(list: List[(String, Int)], x: (String, Int), n: Int) = { if (list.size < n) list :+ x else { val (before, after) = list.span(_._2 >= x._2) if (after.isEmpty) list else before ++ after.tail :+ x } } Another version that always removes the minimum, if that's less than x. def method(list: List[(String, Int)], x: (String, Int), n: Int) = { if (list.size < n) list :+ x else { val smallest = list.minBy(_._2) if (smallest._2 < x._2) { val (before, after) = list.span(_ != smallest) before ++ after.tail :+ x } else list } } and its test results val l1 = List(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : List[(String, Int)] = List((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : List[(String, Int)] = List((three,3), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : List[(String, Int)] = List((one,1), (three,3)) but as I say in a comment, better to use a method that processes the whole sequence of Xs and returns the top N.
I would separate the ordering from the method itself: def method[A: Ordering](list: List[A], x: A, n: Int) = ... What do you want to do if the list contains more than one element less than x? If you're happy with replacing all of them, you could use map rather than your handwritten loop: list map { case a if Ordering.lt(a, x) => x case a => a } If you only want to replace the smallest element of the list, maybe it's neater to use min? val m = list.min if(m < x) { val (init, m :: tail) = list.splitAt(list.indexOf(m)) init ::: x :: tail else list
Removing value from range
I have the following case class: case class objRanges(rangeVals:List[rangeNums]) where rangeNums represents a range of values and is also a case class: case class rangeNums(lowValue:Int, highValue:Int) I would like to implement a subtraction method for objRanges, one with the following signature: def -(numberRemove:Int): objRanges = { The number would then be removed from all the ranges in the list rangeVals, splitting rangeNums that contain the number into two rangeNums (one from lowValue to n-1 and another from n+1 to highValue). Would this be easier to implement using a for comprehension or foldLeft? For example, rangeVals currently holds the elements: [(1,3),(5,10)] Calling the - method with 7 as a parameter should return a new instance of objRanges with the elements: [(1,3),(5,6),(8,10)] While subtracting an element which is the lower bound of a range should just increase the lower bound by one, so subtracting 5 in the rangeVals should return: [(1,3),(6,10)] The same applies for the upper bound. If rangeVals currently holds: [(1,3),(5,7)] Then removing 7 should return [(1,3),(5,6)] The last boundary case would be where there is only one number in a range, and that number is to be deleted. For example, if RangeVals currently holds: [(1,3),(7,7)] Removing 7 should just remove the entire range, returning a new instance with rangeVals equal to: [(1,3)] And how would the solution change if I was looking instead to remove all numbers in the ranges less than numberRemove?
Using map: case class RangeNums(lowValue: Int, highValue: Int) case class ObjRanges(rangeVals: List[RangeNums]) { def -(n: Int): ObjRanges = { val res = rangeVals.map { case e # RangeNums(l, h) => if (n > l && n < h) RangeNums(l, n - 1) :: RangeNums(n + 1, h) :: Nil else if (n == l) RangeNums(l + 1, h) :: Nil else if (n == h) Nil else e :: Nil }.flatten ObjRanges(res) } } test with REPL: scala> val l = RangeNums(0, 10) :: RangeNums(1, 3) :: Nil l: List[RangeNums] = List(RangeNums(0,10), RangeNums(1,3)) scala> val r = ObjRanges(l) r: ObjRanges = ObjRanges(List(RangeNums(0,10), RangeNums(1,3))) scala> r - 5 res0: ObjRanges = ObjRanges(List(RangeNums(0,4), RangeNums(6,10), RangeNums(1,3))) scala> r - 2 res1: ObjRanges = ObjRanges(List(RangeNums(0,1), RangeNums(3,10), RangeNums(1,1), RangeNums(3,3))) scala> r - 10 res2: ObjRanges = ObjRanges(List(RangeNums(1,3))) scala> r - 0 res3: ObjRanges = ObjRanges(List(RangeNums(1,10), RangeNums(1,3))) A tailrec solution: import scala.annotation.tailrec case class ObjRanges(rangeVals: List[RangeNums]) { def -(n: Int): ObjRanges = { #tailrec def minRec(n: Int, rem: List[RangeNums], accu: List[RangeNums]): List[RangeNums] = rem match { case (e # RangeNums(l, h)) :: t => val tmpRes = if (n > l && n < h) RangeNums(n + 1, h) :: RangeNums(l, n - 1) :: accu else if (n == l) RangeNums(l + 1, h) :: accu else if (n == h) accu else e :: accu minRec(n, t, tmpRes) case Nil => accu } ObjRanges(minRec(n, rangeVals, Nil).reverse) } } Using fold: case class ObjRanges(rangeVals: List[RangeNums]) { def -(n: Int): ObjRanges = { def minF(accu: List[RangeNums], e: RangeNums) = { val l = e.lowValue val h = e.highValue if (n > l && n < h) RangeNums(n + 1, h) :: RangeNums(l, n - 1) :: accu else if (n == l) RangeNums(l + 1, h) :: accu else if (n == h) accu else e :: accu } val res = (List[RangeNums]() /: rangeVals)((accu, e) => minF(accu, e)) ObjRanges(res.reverse) } }
How to find the largest element in a list of integers recursively?
I'm trying to write a function which will recursively find the largest element in a list of integers. I know how to do this in Java, but can't understand how to do this at Scala. Here is what I have so far, but without recursion: def max(xs: List[Int]): Int = { if (xs.isEmpty) throw new java.util.NoSuchElementException(); else xs.max; } How can we find it recursively with Scala semantic.
This is the most minimal recursive implementation of max I've ever been able to think up: def max(xs: List[Int]): Option[Int] = xs match { case Nil => None case List(x: Int) => Some(x) case x :: y :: rest => max( (if (x > y) x else y) :: rest ) } It works by comparing the first two elements on the list, discarding the smaller (or the first, if both are equal) and then calling itself on the remaining list. Eventually, this will reduce the list to one element which must be the largest. I return an Option to deal with the case of being given an empty list without throwing an exception - which forces the calling code to recognise the possibility and deal with it (up to the caller if they want to throw an exception). If you want it to be more generic, it should be written like this: def max[A <% Ordered[A]](xs: List[A]): Option[A] = xs match { case Nil => None case x :: Nil => Some(x) case x :: y :: rest => max( (if (x > y) x else y) :: rest ) } Which will work with any type which either extends the Ordered trait or for which there is an implicit conversion from A to Ordered[A] in scope. So by default it works for Int, BigInt, Char, String and so on, because scala.Predef defines conversions for them. We can become yet more generic like this: def max[A <% Ordered[A]](xs: Seq[A]): Option[A] = xs match { case s if s.isEmpty || !s.hasDefiniteSize => None case s if s.size == 1 => Some(s(0)) case s if s(0) <= s(1) => max(s drop 1) case s => max((s drop 1).updated(0, s(0))) } Which will work not just with lists but vectors and any other collection which extends the Seq trait. Note that I had to add a check to see if the sequence actually has a definite size - it might be an infinite stream, so we back away if that might be the case. If you are sure your stream will have a definite size, you can always force it before calling this function - it's going to work through the whole stream anyway. See notes at the end for why I really would not want to return None for an indefinite stream, though. I'm doing it here purely for simplicity. But this doesn't work for sets and maps. What to do? The next common supertype is Iterable, but that doesn't support updated or anything equivalent. Anything we construct might be very poorly performing for the actual type. So my clean no-helper-function recursion breaks down. We could change to using a helper function but there are plenty of examples in the other answers and I'm going to stick with a one-simple-function approach. So at this point, we can to switch to reduceLeft (and while we are at it, let's go for `Traversable' and cater for all collections): def max[A <% Ordered[A]](xs: Traversable[A]): Option[A] = { if (xs.hasDefiniteSize) xs reduceLeftOption({(b, a) => if (a >= b) a else b}) else None } but if you don't consider reduceLeft recursive, we can do this: def max[A <% Ordered[A]](xs: Traversable[A]): Option[A] = xs match { case i if i.isEmpty => None case i if i.size == 1 => Some(i.head) case i if (i collect { case x if x > i.head => x }).isEmpty => Some(i.head) case _ => max(xs collect { case x if x > xs.head => x }) } It uses the collect combinator to avoid some clumsy method of bodging a new Iterator out of xs.head and xs drop 2. Either of these will work safely with almost any collection of anything which has an order. Examples: scala> max(Map(1 -> "two", 3 -> "Nine", 8 -> "carrot")) res1: Option[(Int, String)] = Some((8,carrot)) scala> max("Supercalifragilisticexpialidocious") res2: Option[Char] = Some(x) I don't usually give these others as examples, because it requires more expert knowledge of Scala. Also, do remember that the basic Traversable trait provides a max method, so this is all just for practice ;) Note: I hope that all my examples show how careful choice of the sequence of your case expressions can make each individual case expression as simple as possible. More Important Note: Oh, also, while I am intensely comfortable returning None for an input of Nil, in practice I'd be strongly inclined to throw an exception for hasDefiniteSize == false. Firstly, a finite stream could have a definite or non-definite size dependent purely on the sequence of evaluation and this function would effectively randomly return Option in those cases - which could take a long time to track down. Secondly, I would want people to be able to differentiate between having passed Nil and having passed truly risk input (that is, an infinite stream). I only returned Option in these demonstrations to keep the code as simple as possible.
The easiest approach would be to use max function of TraversableOnce trait, as follows, val list = (1 to 10).toList list.max to guard against the emptiness you can do something like this, if(list.empty) None else Some(list.max) Above will give you an Option[Int] My second approach would be using foldLeft (list foldLeft None)((o, i) => o.fold(Some(i))(j => Some(Math.max(i, j)))) or if you know a default value to be returned in case of empty list, this will become more simpler. val default = 0 (list foldLeft default)(Math.max) Anyway since your requirement is to do it in recursive manner, I propose following, def recur(list:List[Int], i:Option[Int] = None):Option[Int] = list match { case Nil => i case x :: xs => recur(xs, i.fold(Some(x))(j => Some(Math.max(j, x)))) } or as default case, val default = 0 def recur(list:List[Int], i:Int = default):Int = list match { case Nil => i case x :: xs => recur(xs, i.fold(x)(j => Math.max(j, x))) } Note that, this is tail recursive. Therefore stack is also saved.
If you want functional approach to this problem then use reduceLeft: def max(xs: List[Int]) = { if (xs.isEmpty) throw new NoSuchElementException xs.reduceLeft((x, y) => if (x > y) x else y) } This function specific for list of ints, if you need more general approach then use Ordering typeclass: def max[A](xs: List[A])(implicit cmp: Ordering[A]): A = { if (xs.isEmpty) throw new NoSuchElementException xs.reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y) } reduceLeft is a higher-order function, which takes a function of type (A, A) => A, it this case it takes two ints, compares them and returns the bigger one.
You could use pattern matching like that def max(xs: List[Int]): Int = xs match { case Nil => throw new NoSuchElementException("The list is empty") case x :: Nil => x case x :: tail => x.max(max(tail)) //x.max is Integer's class method }
Scala is a functional language whereby one is encourage to think recursively. My solution as below. I recur it base on your given method. def max(xs: List[Int]): Int = { if(xs.isEmpty == true) 0 else{ val maxVal= max(xs.tail) if(maxVal >= xs.head) maxVal else xs.head } } Updated my solution to tail recursive thanks to suggestions. def max(xs: List[Int]): Int = { def _max(xs: List[Int], maxNum: Int): Int = { if (xs.isEmpty) maxNum else { val max = { if (maxNum >= xs.head) maxNum else xs.head } _max(xs.tail, max) } } _max(xs.tail, xs.head) }
I used just head() and tail() def max(xs: List[Int]): Int = { if (xs.isEmpty) throw new NoSuchElementException else maxRecursive(xs.tail, xs.head) } def maxRecursive(xs: List[Int], largest: Int): Int = { if (!xs.isEmpty) { if (xs.head > largest) maxRecursive(xs.tail, xs.head) else maxRecursive(xs.tail, largest) } else { largest } } Here is tests for this logic: test("max of a few numbers") { assert(max(List(3, 7, 2, 1, 10)) === 10) assert(max(List(3, -7, 2, -1, -10)) === 3) assert(max(List(-3, -7, -2, -5, -10)) === -2) }
Folding can help: if(xs.isEmpty) throw new NoSuchElementException else (Int.MinValue /: xs)((max, value) => math.max(max, value)) List and pattern matching (updated, thanks to #x3ro) def max(xs:List[Int], defaultValue: =>Int):Int = { #tailrec def max0(xs:List[Int], maxSoFar:Int):Int = xs match { case Nil => maxSoFar case head::tail => max0(tail, math.max(maxSoFar, head)) } if(xs.isEmpty) defaultValue else max0(xs, Int.MinValue) } (This solution does not create Option instance every time. Also it is tail-recursive and will be as fast as an imperative solution.)
Looks like you're just starting out with scala so I try to give you the simplest answer to your answer, how do it recursively: def max(xs: List[Int]): Int = { def maxrec(currentMax : Int, l: List[Int]): Int = l match { case Nil => currentMax case head::tail => maxrec(head.max(currentMax), tail) //get max of head and curretn max } maxrec(xs.head, xs) } This method defines an own inner method (maxrec) to take care of the recursiveness. It will fail ( exception) it you give it an empty list ( there's no maximum on an empty List)
Here is my code (I am a newbie in functional programming) and I'm assuming whoever lands up under this question will be folks like me. The top answer, while great, is bit too much for newbies to take! So, here is my simple answer. Note that I was asked (as part of a Course) to do this using only head and tail. /** * This method returns the largest element in a list of integers. If the * list `xs` is empty it throws a `java.util.NoSuchElementException`. * * #param xs A list of natural numbers * #return The largest element in `xs` * #throws java.util.NoSuchElementException if `xs` is an empty list */ #throws(classOf[java.util.NoSuchElementException]) def max(xs: List[Int]): Int = find_max(xs.head, xs.tail) def find_max(max: Int, xs: List[Int]): Int = if (xs.isEmpty) max else if (max >= xs.head) find_max(max, xs.tail) else find_max(xs.head, xs.tail) Some tests: test("max of a few numbers") { assert(max(List(3, 7, 2)) === 7) intercept[NoSuchElementException] { max(List()) } assert(max(List(31,2,3,-31,1,2,-1,0,24,1,21,22)) === 31) assert(max(List(2,31,3,-31,1,2,-1,0,24,1,21,22)) === 31) assert(max(List(2,3,-31,1,2,-1,0,24,1,21,22,31)) === 31) assert(max(List(Int.MaxValue,2,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,222,3,-31,1,2,-1,0,24,1,21,22)) === Int.MaxValue) }
list.sortWith(_ > ).head & list.sortWith( > _).reverse.head for greatest and smallest number
If you are required to write a recursive max function on a list using isEmpty, head and tail and throw exception for empty list: def max(xs: List[Int]): Int = if (xs.isEmpty) throw new NoSuchElementException("max of empty list") else if (xs.tail.isEmpty) xs.head else if (xs.head > xs.tail.head) max(xs.head :: xs.tail.tail) else max(xs.tail) if you were to use max function on list it is simply (you don't need to write your own recursive function): val maxInt = List(1, 2, 3, 4).max
def max(xs: List[Int]): Int = { def _max(xs: List[Int], maxAcc:Int): Int = { if ( xs.isEmpty ) maxAcc else _max( xs.tail, Math.max( maxAcc, xs.head ) ) // tail call recursive } if ( xs.isEmpty ) throw new NoSuchElementException() else _max( xs, Int.MinValue ); }
With tail-recursion #tailrec def findMax(x: List[Int]):Int = x match { case a :: Nil => a case a :: b :: c => findMax( (if (a > b) a else b) ::c) }
With pattern matching to find max and return zero in case empty def findMax(list: List[Int]) = { def max(list: List[Int], n: Int) : Int = list match { case h :: t => max(t, if(h > n) h else n) case _ => n } max(list,0) }
I presume this is for the progfun-example This is the simplest recursive solution I could come up with def max(xs: List[Int]): Int = { if (xs.isEmpty) throw new NoSuchElementException("The list is empty") val tail = xs.tail if (!tail.isEmpty) maxOfTwo(xs.head, max(xs.tail)) else xs.head } def maxOfTwo(x: Int, y: Int): Int = { if (x >= y) x else y }
def max(xs: List[Int]): Int = xs match { case Nil => throw new NoSuchElementException("empty list!") case x :: Nil => x case x :: tail => if (x > max(tail)) x else max(tail) }