Skip to content

Instantly share code, notes, and snippets.

@pedrofurla
Last active October 9, 2018 00:51
Show Gist options
  • Save pedrofurla/bc6be26dc3a70d397ad3d9881d3e7f42 to your computer and use it in GitHub Desktop.
Save pedrofurla/bc6be26dc3a70d397ad3d9881d3e7f42 to your computer and use it in GitHub Desktop.
So, a shop that claims to be doing FP thinks this is too functional
object Nth extends App {
// Problem: given two sorted lists (`as` and `bs` below) find the nth smaller element.
// It's assumed that `k <= as.length + bs.length`.
def nth(as:List[Int], bs:List[Int], k:Int):Int = (as, bs) match {
case (Nil, Nil) => ???
case (a :: as, b :: bs) if k==0 => Math.min(a,b)
case (a :: as, b :: bs) if a < b => nth(as, b :: bs, k-1)
case (a :: as, b :: bs) if a > b => nth(a :: as, bs, k-1)
case (a :: as, Nil) => if(k==0) a else nth(as, Nil, k-1)
case (Nil, b :: bs) => if(k==0) b else nth(Nil, bs, k-1)
}
val as0 = List(1,2,5,10)
val bs0 = List(3,100,1000)
(0 to 6).foreach{ k=>
print("k: "+k)
println(" nth: "+nth(as0,bs0,k))
}
println()
try { nth(as0,bs0,7) } catch { case a => println("OPS 7 "+a.getMessage) }
try { nth(as0,bs0,-1) } catch { case a => println("OPS -1 "+a.getMessage) }
println("------ nth(as1,bs1,k):")
val as1 = List(1,2,3,4)
val bs1 = List(5,6,7,8,9)
(0 to 8).foreach{ k=>
print("k: "+k)
println(" nth: "+nth(as1,bs1,k))
}
println("------ nth(bs1,as1,k):")
(0 to 8).foreach{ k=>
print("k: "+k)
println(" nth: "+nth(bs1,as1,k))
}
}
@pedrofurla
Copy link
Author

In companie's words this is "hard core pure FP"

@tonymorris
Copy link

Sucks to be that company. Make your own company and beat them competitively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment