write Scala iterative recursion like Python generator -


i can write recursion return iterator in python using generator.

like permutation function string:

def permute(string):     if len(string)==1:         yield string     else:         in range(len(string)):             p in permute(string[:i]+string[i+1:]):                 yield string[i]+p 

how translate scala version. can scala's iterator work here, or need resort continuation(never used, heard of )?

you can use stream similar effect:

def permute[t](list: list[t]): stream[list[t]] =   if (list.size == 1) stream(list)   else {     <- stream.range(0, list.size)     l <- list splitat match {       case (left, el :: right) => permute(left ::: right) map (el :: _)     }   } yield l 

it works ok permutations of long sequences. example, printing last 10 elements 10 permutations of 100 elements starting 10000-th permutation:

scala> permute(1 100 tolist) slice (10000, 10010) foreach {   lst => println(lst.takeright(10)) } list(91, 92, 94, 100, 99, 95, 97, 98, 93, 96) list(91, 92, 94, 100, 99, 95, 97, 98, 96, 93) list(91, 92, 94, 100, 99, 95, 98, 93, 96, 97) list(91, 92, 94, 100, 99, 95, 98, 93, 97, 96) list(91, 92, 94, 100, 99, 95, 98, 96, 93, 97) list(91, 92, 94, 100, 99, 95, 98, 96, 97, 93) list(91, 92, 94, 100, 99, 95, 98, 97, 93, 96) list(91, 92, 94, 100, 99, 95, 98, 97, 96, 93) list(91, 92, 94, 100, 99, 96, 93, 95, 97, 98) list(91, 92, 94, 100, 99, 96, 93, 95, 98, 97) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -