1

Looking at the Scala standart library I 've noticed that many of the functions(methods) are written in imperative style : loops are used more often than tailrec and so on. For example:

@inline final override def takeWhile(p: A => Boolean): List[A] = {
    val b = new ListBuffer[A]
    var these = this
    while (!these.isEmpty && p(these.head)) {
      b += these.head
      these = these.tail
    }
    b.toList
   }

Can be easily rewritten(as function):

def takeWhile[A](p:A=>Boolean)(l:List[A]): List[A] ={
@tailrec
def takeWh(p:A=>Boolean,l:List[A],r:List[A]):List[A]={
  if(l.isEmpty) r
  else if(p(l.head)) takeWh(p,l.tail,l.head::r)
  else r
}
takeWh(p,l,Nil).reverse
}

Why Scala developers prefer imperative style over functional if Scala is supposed to be a functional language?

ig-melnyk
  • 2,769
  • 2
  • 25
  • 35
  • 6
    [Scala Performance: imperative vs functional style](http://stackoverflow.com/questions/3328345/scala-performance-imperative-vs-functional-style) – Alex K. Aug 22 '14 at 13:32
  • 1
    @Theolodis, there's no need to be rude. Calm down. – Gabriele Petronella Aug 22 '14 at 13:34
  • @GabrielePetronella How am I rude? What do you mean by "calm down"? Because of the bold part? It's just for better readability.... – Theolodis Aug 22 '14 at 13:41
  • @AlexK. Of course,"functional" qsort is really bad(Actually it can easily run O(n^2) ). Before writing a post I 've looked at Haskell library(which is purely functional) and they use 'naive' implementation of takeWhile. Scala's dropWhile function is written using tailrecursion - I wonder why they use imperative style here. Here's a link https://github.com/scala/scala/blob/2.11.x/src/library/scala/collection/immutable/List.scala – ig-melnyk Aug 22 '14 at 13:41
  • 1
    I think the time complexity of `r:::List(x)` is bad. Overall, is the timecomplexity of both implementation the same? – Naetmul Aug 22 '14 at 14:01
  • @Naetmul you 're right . I ll change my implementation without using r:::List(x). Now it runs something slower than standart implementation. – ig-melnyk Aug 22 '14 at 14:07
  • @ig-melnyk You know, using immutable objects in functional programming has a lot of advantages like thread-safe. But in performance perspective, it will negatively affect due to many object creation - which will take both time and memory. Mutable objects do not fit in functional programming as immutable ones do. I think the code is the result of the developers' decision between immutable ones' safety and mutable ones' speed. – Naetmul Aug 22 '14 at 14:14
  • @ig-melnyk by the way, it's not only so in scala -- even though erlang is stricter from mutability point of view, [it's underpinnings (NIFs) are implemented via mutable C code](http://www.erlang.org/doc/tutorial/nif.html). – om-nom-nom Aug 22 '14 at 14:25

0 Answers0