recursion - Integer to Binary in scala -


just kicks decided write snippet takes integer , converts binary. seems performing conversion wondering if there's might missing this. great feedback.

thanks

def converttobinary(n: int, bin: list[int]): string = {   if(n/2 == 1) {     (1::(n%2)::bin).mkstring(" ")   } else {      val r = n%2;val q = n/2;converttobinary(q,r::bin)   } } 

1) formatting :-)

def converttobinary(n:int, bin:list[int]):string = {   if(n/2 == 1) (1:: (n % 2) :: bin).mkstring(" ")   else {     val r = n % 2;     val q = n / 2;     converttobinary(q, r::bin)   } } 

2) signature:

i omit convert part, made accumulator optional parameter (function user doesn't have supply arguments used internal implementation, right?)

def tobinary(n:int, bin: list[int] = list.empty[int]): string = {   if(n/2 == 1) (1:: (n % 2) :: bin).mkstring(" ")   else {     val r = n % 2     val q = n / 2     tobinary(q, r::bin)   } } 

now can used as:

val str = tobinary(42) 

somebody might propose pimp such function, call might

val str = 42.tobinary // btw, there such function in std lib: 42.tobinarystring 

but don't see profit.

the other thing bothers me you're using list & mkstring purpose, why not stringbuilder? q , r?

and final minor point -- place @annotation.tailrec ensure function optimized in case of future changes


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -