Monads and Decorator pattern - java

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.

Related

Why does Java use -> instead of => for lambda functions?

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.

Java lambda expression best practices

Java stream operators can sometimes become very cumbersome and hard to debug. Is there a best practice guideline as to how complex your lambda expression should be beyond which it is better to write an elaborate multi-statement piece of code?
For example, I came across below two statement code for finding factorial which was hard to understand:
Stream<Pair> allFactorials = Stream.iterate(
new Pair(BigInteger.ONE, BigInteger.ONE),
x -> new Pair(
x.num.add(BigInteger.ONE),
x.value.multiply(x.num.add(BigInteger.ONE))));
return allFactorials.filter(
(x) -> x.num.equals(num)).findAny().get().value;
Java streams are not a silver bullet and you don't have to use it everywhere. There are a lot of cases where you could solve the problem using standard for loop approach.
As for your code.. It is a good example where streams complicate the code and make it hard to understand/maintain. But still there are few solutions are more readable.
Take a look:
calculating factorial using Java 8 IntStream?

Formula manipulation algorithm

I am wanting to make a program that will when given a formula, it can manipulate the formula to make any value (or in the case of a simultaneous formula, a common value) the subject of the formula.
For example if given:
a + b = c
d + b = c
The program should therefore say:
b = c - a, d = c - b etc.
I'm not sure if java can do this automatically or not when I give the original formula as input. I am not really interested in solving the equation and getting the result of each variable, I am just interested in returning a manipulated formula.
Please let me know if I need to make an algorithm or not for this, and if so, how would I go about doing this. Also, if there are any helpful links that you might have, please post them.
Regards
Take a look at JavaCC. It's a little daunting at first but it's the right tool for something like this. Plus there are already examples of what you are trying to achieve.
Not sure what exactly you are after, but this problem in its general problem is hard. Very hard.
In fact, given a set of "formulas" (axioms), and deduction rules (mathematical equivalence operations), we cannot deduce if a given formula is correct or not. This problem is actually undecideable.
This issue was first addressed by Hilbert as Entscheidungsproblem
I read a book called Fluid Concepts and Creative Analogies by Douglas Hofstadter that talked about this sort of algebraic manipulations that would automatically rewrite equations in other ways attempting to join equations to other equations an infinite (yet restricted) number of ways given rules. It was an attempt to prove yet unproven theorems/proofs by brute force.
http://en.wikipedia.org/wiki/Fluid_Concepts_and_Creative_Analogies
Douglas Hofstadter's Numbo program attempts to do what you want. He doesn't give you the source, only describes how it works in detail.
It sounds like you want a program to do what highschool students do when they solve algebraic problems to move from a position where you know something, modifying it and combining it with other equations, to prove something previously unknown. It takes a strong Artificial intelligence to do this. The part of your brain that does this is the Neo Cortex, which does science, and it's operating principle is as of yet not understood.
If you want something that will do what college students do when they manipulate equations in calculus, you'll have to build a fairly strong artificial intelligence.
http://en.wikipedia.org/wiki/Neocortex
When we can do whole-brain emulation of a human neo cortex, I will post the answer here.
Yes, you need to write some algorithm to do this kind of computer algebra. At least
a parser to interpret the input
an algebra model to relate parsed operands ('a', 'b', ...) and operator ('+', '=')
implement any appropriate rule to support the manipulation you wish to do

Should I change to scala to create a system with rewrite rules?

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.

Is Scala a Functional Programming Language? [closed]

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? :-)

Categories