The Artima Developer Community
Sponsored Link

Scala Buzz
Scala: breaking/chunking a list into list of list

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Zemian Deng

Posts: 49
Nickname: zdeng
Registered: Jan, 2008

Zemian Deng is the creator of SweetScala web framework
Scala: breaking/chunking a list into list of list Posted: Nov 16, 2008 1:30 PM
Reply to this message Reply

This post originated from an RSS feed registered with Scala Buzz by Zemian Deng.
Original Post: Scala: breaking/chunking a list into list of list
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Zemian Deng
Latest Posts From thebugslayer

Advertisement
Q: Break a list into list of list for certain size.
List(1,2,3,4,5,6).chunk(2) == List(List(1,2), List(3,4), List(5,6))
List(1,2,3,4,5,6).chunk(4) == List(List(1,2,3,4), List(5,6))
A:
class ListHelper[T](ls : List[T]) {
  /** @param size  The size of each sub list */
  def chunk(size : Int) =  List.range(0, ls.size, size).map{ i => ls.slice(i, i+size) }
}
object ListHelper {
  implicit def list2helper[T](ls : List[T]) = new ListHelper(ls)
}

//test
import ListHelper.list2helper
assert(List(1,2,3,4,5,6).chunk(2) == List(List(1,2), List(3,4), List(5,6)))
assert(List(1,2,3,4,5,6).chunk(4) == List(List(1,2,3,4), List(5,6)))
println("passed")
Notes:

Some prefer the parameter to specify the number of pieces when divided rather than the size of each chunk. Just different variation I guess.

Also, this can be seen as undoing the List.flatMap's work.

You can use above to turn a list into map like this:

//turn a list to map
val m = Map() ++ List(1,2,3,4,5,6).chunk(2).map{ xs => (xs(0), xs(1)) }
println(m) // output: Map(1 -> 2, 3 -> 4, 5 -> 6)

Read: Scala: breaking/chunking a list into list of list

Topic: Sorting a map by it's value Previous Topic   Next Topic Topic: BASE Meeting #7

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use