Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why List partition works while span does not

Tags:

scala

I have this List oX of (Char, Int) pars (it contains pairs with only unique Char values)

List(( ,3), (d,1), (e,3), (h,3), (i,1) , (l,3), (o,2), (r,2), (t,1), (w,1))

I need to partition this list into 2 - one that contains any pair that has 'd' Char and another is the rest.

So I tried partition and span but found that span does not work as expected. Here are the results (copied from scala worksheet)

 val myPartition = oX.partition(e => e._1 == 'd') > myPartition  : (List[(Char, Int)], List[(Char, Int)]) = (List((d,1)),List(( ,3), (e,3), (h,3), (i,1), (l,3), (o,2), (r,2), (t,1), (w,1)))

  val mySpan = oX.span(e => e._1 == 'd') > mySpan  : (List[(Char, Int)], List[(Char, Int)]) = (List(),List(( ,3), (d,1), (e,3), (h,3), (i,1), (l,3), (o,2), (r,2), (t,1), (w,1)))

I am puzzled why given same predicate functino partition gives me expected result while span gives me empty List as first list and copy of original as second list

like image 910
Dmitri Avatar asked Oct 15 '25 16:10

Dmitri


1 Answers

From the documentation of span: "Returns the longest prefix of the list whose elements all satisfy the given predicate, and the rest of the list."

So here span gives you the expected result: since the first tuple in your list doesn't have the character d, the longest prefix of the list where each tuple has the character d is indeed the empty list.

like image 94
noziar Avatar answered Oct 18 '25 07:10

noziar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!