As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've learned programming from Java, then tried to learn one programming language per year, second was C++, then Python. It came to learn next one, I looked for something new, I choose Scala because it was compatible with Java and could be some transition from OOP to Functional Programming.
It was cool, learning new paradigms, new style and new way of thinking. It was great experience just read about elegant Scala concepts, and much better to code on Scala.
Reading a lot of articles I faced this article criticizing Scala:
Scala is not a functional programming language. It is a statically typed object oriented language with closures.
After reading this articles some doubts came to me, I really like Scala and was starting to write on Scala more, but is Scala suits definition of Functional Programming? Is that article says truth or just faking readers? Must I learn Haskell or some other Functional Programming Language to really experience FP?
UPDATE: Expecting rational answers with good examples, without causing disputes.
Scala does not force you to write in a functional style. This is perfectly valid Scala:
var i = 1
while (i < 10) {
println("I like side effects, this is number "+i)
i += 1
}
case class C(var i: Int, var set: Boolean = false)
def setMe(c: C) = { if (!c.set) { c.set = true; c.i += 1 }; c }
setMe(C(5))
So in this sense, horrors, Scala is not functional! Side effects galore, mutable state--everything you can do in Java you can do in Scala.
Nonetheless, Scala permits you to code in functional style, and makes your life easier (than in Java) in a number of ways:
There are first-class functions
There is an immutable collections library
Tail recursion is supported (to the extent that the JVM can manage)
Pattern matching is supported
(etc.)
This looks somewhat more functional:
for (i <- 1 to 10) println("Sometimes side effects are a necessary evil; this is number"+i)
case class C(i: Int, set: Boolean = false)
def setIt(c: C, f: Int=>Int) = C(f(c.i), true)
setIt(C(5), _+1)
It's worth noting that the author of that particular article seems to have a very poor understanding of Scala; pretty much every example that looks ugly in his hands is unnecessarily ugly. For example, he writes
def x(a: Int, b: Int) = a + b
def y = Function.curried(x _)(1)
But it's not that bad, if you pay attention to what you're doing:
def x(a: Int)(b: Int) = a + b
val y = x(1) _
Anyway, the bottom line is that Scala is not a pure functional programming language, and as such, its syntax is not always ideal for functional programming since there are other considerations at play. It does have virtually all of the standard features that one expects from a functional programming language, however.
Scala is a multi-paradigm programming
language designed to integrate
features of object-oriented
programming and functional
programming.
I couldn't say it any better and that's all there is to say except for pointless arguments.
My personal litmus test for a functional language is Church numerals.
Scheme example:
(define (thrice f)
(lambda (x)
(f (f (f x))))))
((thrice 1+) 0)
=> 3
(1+ is a Scheme function that adds 1 to its argument. thrice takes a function f and returns a function that composes f with itself three times. So (thrice 1+) adds three to its argument.)
((thrice (thrice 1+)) 0)
=> 9
(Since (thrice 1+) is a function that adds three, taking the thrice of that gives a function that adds nine.)
And my favorite:
(((thrice thrice) 1+) 0)
=> 27
(Reasoning left as an exercise for the reader. This last example is the most important.)
If you cannot write this example in your language without horrible contortions, then I say it is not a functional language (example: C/C++).
If you can write this example in your language, but it looks very unnatural, then I say your language "supports functional programming" but is not really a functional language (example: Perl).
If this example ports neatly to your language and actually looks not too different from how you use it day to day, then it's a functional language.
I do not know Scala. Anybody want to tell me where it fits? :-)
Related
I am a .NET and JavaScript developer. Now I am working in Java, too.
In .NET LINQ and JavaScript arrow functions we have =>.
I know Java lambdas are not the same, but they are very similar. Are there any reasons (technical or non technical) that made java choose -> instead of =>?
On September 8, 2011, Brian Goetz of Oracle announced to the OpenJDK mailing list that the syntax for lambdas in Java had been mostly decided, but some of the "fine points" like which type of arrow to use were still up in the air:
This just in: the EG has (mostly) made a decision on syntax.
After considering a number of alternatives, we decided to essentially
adopt the C# syntax. We may still deliberate further on the fine points
(e.g., thin arrow vs fat arrow, special nilary form, etc), and have not
yet come to a decision on method reference syntax.
On September 27, 2011, Brian posted another update, announcing that the -> arrow would be used, in preference to C#'s (and the Java prototype's) usage of =>:
Update on syntax: the EG has chosen to stick with the -> form of the
arrow that the prototype currently uses, rather than adopt the =>.
He goes on to provide some description of the rationale considered by the committee:
You could think of this in two ways (I'm sure I'll hear both):
This is much better, as it avoids some really bad interactions with existing operators, such as:
x => x.age <= 0; // duelling arrows
or
Predicate p = x => x.size == 0; // duelling equals
What a bunch of idiots we are, in that we claimed the goal of doing what other languages did, and then made gratuitous changes "just for the sake of doing something different".
Obviously we don't think we're idiots, but everyone can have an opinion :)
In the end, this was viewed as a small tweak to avoid some undesirable
interactions, while preserving the overall goal of "mostly looks like
what lambdas look like in other similar languages."
Howard Lovatt replied in approval of the decision to prefer ->, writing that he "ha[s] had trouble reading Scala code". Paul Benedict of Apache concurred:
I am glad too. Being consistent with other languages is a laudable goal, but
since programming languages aren't identical, the needs for Java can lead to
a different conclusion. The fat arrow syntax does look odd; I admit it. So
in terms of vanity, I am glad to see that punted. The equals character is
just too strongly associated with assignment and equality.
Paigan Jadoth chimed in, too:
I find the "->" much better than "=>". If arrowlings at all instead of the
more regular "#(){...}" pattern, then something definitely distinct from the
gte/lte tokens is clearly better. And "because the others do that" has never
been a good argument, anyway :D.
In summary, then, after considering arguments on both sides, the committee felt that consistency with other languages (=> is used in Scala and C#) was less compelling than clear differentiation from the equality operators, which made -> win out.
But Lieven Lemiengre was skeptical:
Other languages (such as Scala or Groovy) don't have this problem because
they support some placeholder syntax.
In reality you don't write "x => x.age <= 0;"
But this is very common "someList.partition(x => x.age <= 18)" and I agree
this looks bad. Other languages make this clearer using placeholder syntax
"someList.partition(_.age <= 18)" or "someList.partition(it.age <= 18)"
I hope you are considering something like this, these little closures will
be used a lot!
(And I don't think replacing '=>' with '->' will help a lot)
Other than Lieven, I didn't see anyone who criticized the choice of -> and defended => replying on that mailing list. Of course, as Brian predicted, there were almost certainly opinions on both sides, but ultimately, a choice just has to be made in these types of matters, and the committee made the one they did for the stated reasons.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In many cases, mostly when you are looping through an array and assigning values to the elements, there is a scope to use post increment operator. Is it considered a good practice.
For example, in the following code where the copying is being done which one is better.
int [] to_assign;
int [] to_include;
int [] from_assign;
// Version 1
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
to_assign[count++] = from_assign[i];
}
// Version 2
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[count] = from_assign[i];
count++;
}
}
It's purely a matter of style. Personally, I'd use whichever one makes the most logical sense. If the increment is logically part of the operation, then use the post-increment. If not, use a separate increment operation.
Also, when you use an increment operator alone, it is generally preferred to use a pre-increment. While it won't matter with simple types like integers, with more complex types, it can be much more efficient in languages like C++ that have operator overloading because a pre-increment doesn't need two instances to be around at the same time. There's no performance impact with Java, because it doesn't have operator overloading, but if you want a consistent style rule, it should be pre-increment rather than post-increment.
I'd argue that the second solution is perhaps slightly cleaner to read. I.e. the eye observes that an assignment is being made, and then that there is an increment. Having them both together on the same line makes it slightly less easy to read at a glance. So, I'd prefer solution two.
That said, this is a matter of preference. I don't think one can speak of an established best or better practice here.
In the days when every last ounce of performance mattered, the first version would have been preferred, because the compiler has a higher change of emitting slightly more optimal assembly in the first solution.
Any good compiler will optimize this for you anyway. All are good as long as they are human-readable.
"++" is a leftover from the days of pointer arithmetic -- there are some of us who prefer "+= 1" for integers. But the compiler should manage simple cases like this correctly, regardless.
Modern compilers optimize this kind of code anyway, so in the end it doesn't matter how and where you're incrementing the variable.
From a style perspective, the first version is smaller, and for some easier to read.
From a code comprehension point of view, the second version is easier to understand for beginner developers.
From a performance point of view, ignoring compiler optimizations, this is even faster:
// Version 3
int count = -1;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[++count] = from_assign[i];
}
}
It's faster because in theory count++ creates a temporary copy of the value before the increment, while ++count increments and uses the same variable. But again, this kind of premature optimization is not needed any more, since compilers can detect such frequent cases and optimizes the generated code.
I'm new to functional programming. While following a tutorial on Monads, I got to think it as the analogy of Decorator pattern in OOP. Am I correct or is there any design pattern that closely resembles Monads ?
Monads are definitely not decorators. There isn't a standard OOP pattern in common use that is a direct analogy of monads. Though you can implement monads in OOP just fine, see e.g.:
http://logicaltypes.blogspot.sg/2011/09/monads-in-java.html
The best Clojure-based monad tutorial I know of is this video series by Brian Marick:
https://vimeo.com/20717301
I suggest watching this through - it's a pretty good introduction with lots of examples.
you can start thinking about monads as about "overridable semicolons", due to the known syntax-sugar in Haskell
in general, that does mean you can have same control structure (code block) doing different things depending on which monad is currently used
qick example in Haskell
import Data.Maybe
import Data.List
funcMaybe x = do
z <- x
return $ z * z
funcList x = do
z <- x
return $ z * z
runMaybe = funcMaybe ( Just 5 )
runList = funcList [ 5, 6 ]
being executed in GHCI, it will prompt
ghci> runMaybe
Just 25
ghci> runList
[25, 36]
as you can see, the same code block produces different results - List in one case and Maybe in another case, wrapped into appropriate data structure
Monads are like a function composition on steroids and there is no similar powerful concept in OO world.
I have some classes that I developed that I am using in a Android application. I have about 6-7 classes in that core, some of them are abstract classes with abstract methods. Those classes were created to provide a API to extend my Android Application.
Now I want to create an extensible system that accepts rewrite rules. Those rules are useful to replace some components at runtime. Imagine a system with mathematical operations where you see all the sums, multiplications, etc. Now you can zoom out and I want to simplify some operations dependending on the zoom level.
My system was built in java, but I belive that scala, with pattern matching, will simplify my problem. However, everytime I look at scala I see a lot of time I have to spend and a lot of headches configuring IDEs...
My classes are built to create structures like this one:
I want to be able to write rules that create a block that contains other blocks. Something like:
Integer Provider + Integer Provider -> Sum Provider
Sum Provider + Sum -> Sum Provider
Rules can be created by programmers. Any element of my structure can also be built by programmers. I don't know if scala simplifies this rule engine system, but I know that this engine, in java, can be boring to build (probly a lot of bugs will be created, I will forget some cases, etc).
Should I change all my system to scala? Or there is away to use only this feature of scala? Does it worth it?
PS: For more information on the structure please see this post at User Experience.
Yes, it is easy to write such rules in Scala, and, in fact, there have been some questions on Stack Overflow related to rule rewriting systems in Scala. Also, there are some libraries that may help you with this, related to strategic programming and nlp, but I haven't used them, so I can't comment much.
Now, I don't know exactly where these classes are coming from. If you are parsing and building them, the parser combinator library can trivially handle it:
sealed trait Expr { def value: Int }
case class Number(value: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr { def value = e1.value + e2.value }
object Example extends scala.util.parsing.combinator.RegexParsers {
def number: Parser[Expr] = """\d+""" ^^ (n => Number(n.toInt))
def sum: Parser[Expr] = number ~ "+" ~ expr ^^ {
case n ~ "+" ~ exp => Sum(n, exp)
}
def expr: Parser[Expr] = sum | number
}
If you have these classes in some other way and are applying simplifications, you could do it like this:
def simplify(expr: List[Expr]): Expr = expr match {
case expr :: Nil =>
List(expr) // no further simplification
case (n1: NumberProvider) :: Plus :: (n2: NumberProvider) :: rest =>
simplify(SumProvider(n1, n2) :: rest)
case (n: NumberProvider) :: Plus :: (s: SumProvider) :: rest =>
simplify(SumProvider(n, s) :: rest)
case (s: SumProvider) :: Plus :: (n: NumberProvider) :: rest =>
simplify(SumProvider(s, n) :: rest)
case other => other // no further simplification possible
}
The important elements here are case classes, extractors and pattern matching.
As a lone developer, Scala is expressive and powerful, so once mastered can be satisfying to write less and do more -- less boilerplate code, more compact idioms.
However, the power of Scala does come at a cost: it is a totally different language, with different (and I'd say more complex) idioms and syntax from Java. Java was designed to be intentionally simple, with the idea being that in larger organizations with more code being shared among developers, explicitness and syntax simplicity are more valuable than brilliantly concise code.
Java made an intentional choice to provide a smaller toolset to make it as quick and easy as possible for one developer to pick up where another left off, so in that sense it's geared towards team development. Scala however gives you a bit more rope to make concise but less immediately obvious constructs, which can be a minus for large enterprise environments.
Currently, Scala also has a smaller developer pool than Java, which means fewer examples and a smaller talent pool if you ever intend to hire a development team.
But as a lone developer on a solo project or in a small tight-knit team, Scala can be fun and fast to code with once you get over the significant learning hump.
If you are switching to Scala switch to it for everything you can. There is hardly a point in using Java.
Is it worth the investment? From what one can read on the web (and my own impression) you won't become faster with Scala, but you will learn a lot.
So if you are only concerned with development speed: ignore Scala.
If you want to learn: Scala is a great choice as the next language to learn and use.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
In near future we might be enforced by a rule by which we can not have any hard coded numbers in our java source code. All the hard coded numbers must be declared as final variables.
Even though this sounds great in theory it is really hard/tedious to implement in code, especially legacy code. Should it really be considered "best practice" to declare numbers in following code snippets as final variables?
//creating excel
cellnum = 0;
//Declaring variables.
Object[] result = new Object[2];
//adding dash to ssn
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9);
Above are just some of the examples I could think of, but in these (and others) where would you as a developer say enough is enough?
I wanted to make this question a community wiki but couldn't see how...?
Definitely no. Literal constants have their places, especially low constants such as 0, 1, 2, ...
I don't think anyone would think
double[] pair = new double[PAIR_COUNT];
makes more sense than
double[] pair = new double[2];
I'd say use final variables if
...it increases readability,
...the value may change (and is used in multiple places), or
...it serves as documentation
A related side note: As always with coding standards / conventions: very few (if any) rules should be followed strictly.
Replacing numbers by constants makes sense if the number carries a meaning that is not inherently obvious by looking at its value alone.
For instance,
productType = 221; // BAD: the number needs to be looked up somewhere to understand its meaning
productType = PRODUCT_TYPE_CONSUMABLE; // GOOD: the constant is self-describing
On the other hand,
int initialCount = 0; // GOOD: in this context zero really means zero
int initialCount = ZERO; // BAD: the number value is clear, and there's no need to add a self-referencing constant name if there's no other meaning
Generally speaking, if a literal has a special meaning, it should be given a unique name rather than assuming things. I'm not sure why it is "practically" hard/tedious to do the same.
Object[] result = new Object[2]; => seems like a good candidate for using a Pair class
cellnum = 0; => cellnum = FIRST_COLUMN; esp since you might end up using an API which treats 1 as the starting index or maybe you want to process an excel in which columns start from 2.
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9) => If you have code like this littered throughout your codebase, you have bigger problems. If this code exists in a single location and is shielded by a sane API, I don't really see a problem here.
I've seen folks consider 0 and 1 accepted exceptions.
The idea is that you want to document why you have two Objects as above for example.
I agree with you about the dashes in SSN. The comment describes it better than 4 named constants.
In general, I like the idea of no magic numbers, but as with every rule, there are pragmatics involved. Legacy code, brings its own issues. It's a lot of work without a lot of productivity in terms of changed behavior to bring old code up to date this way. I would consider doing it in an evolutionary fashion: when you have to edit an old file, bring it up to date.
It really depends on the context doesn't it. If there are numbers in the code that does not indicate why they exist then naming them makes teh code more readable. If you see the number 3.14 in code is it PI? is there any way to tell or is that just a coincidence? Naming it PI will clear up the mystery.
In your example, why is cellnum = 2? why not 10? or 20? That should be named something, say INITIAL_CELL or MAX_CELL. Expecially if this same number, meaning the same thing appears again in the code.
Depends if it needs to be changed. Or for that matter, it can be changed.
If you only need 2 objects (say, for a pair like aioobe mentioned) then that isn't a magic number, it's the correct number. If it's for a variable tuple that, at this moment, is 2, then you probably should abstract it out into a constant.