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.
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.
There is a question with the same title like this on stackoverflow here, but I wanted to ask if it is possible to do something similar to this in Java.
I wanted to make something similar to desmos, just like that guy did in Javascript,but i want to make it in Java using lwjgl 2. I am new to Java and I'd like to know if it is possible to convert a piece of string into a method. Is it possible?
I have looked for possible options and I found out that your can make your own Java eval() method. But I don't want to replace the x in the string for every pixel of the window-width.
Thanks in advance.
What you need is an engine/library that can evaluate expressions, defined as string at execution time. If you wrap the evaluation code into function call (e.g. lambda function), you will get what you need.
Option 1: You can use exp4j. exp4j is a small footprint library, capable of evaluating expressions and functions at execution time. Here is an example:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Option 2: You can use the Java's script engine. You can use it to evaluate expressions defined, for example, in JavaScript:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("sin(1.25)");
Option 3: Compile to native Java. With this approach, you use template to generate .java file with a class that contains your expression. Than you call the Java compiler. This approach has the drawback that has some complexity in the implementation and some initial latency (until the class is compiled), but the performance is the best. Here are some links to explore:
Create dynamic applications with javax.tools
In particular javax.tools.Compiler
Note of Caution Whatever approach you chose, have in mind that you need to think about the security. Allowing the user to enter code which can be evaluated without security restrictions could be very dangerous.
I have defined a grammar through which I produce a series of abstract syntax trees of sorts. For example
x = 7
println + * x 2 5
becomes
(assign)
/ \
x 7
(println)
|
(+)
/ \
(*) 5
/ \
x 2
These trees are made from various Node classes representing values and operations. Now, these trees are easy to interpret but my goal is to generate Java bytecode representing these processes. My question is, what would be the best way to approach that? Should I just literally write various bytecode instructions to a .class file, or is there some library or interface that can help with this sort of thing?
The answer is yes. ASM and BCEL are two Java libraries designed to assist with runtime generation of classfiles.
I have written a framework that lets you compose code with declarative expression trees and then compile them to bytecode. Though I had developed it to ease runtime code generation, it could just as easily be leveraged as a sort of compiler back end, e.g., by translating your syntax tree into one of my expression trees.
At the very least, you could probably glean some useful bits from my compiler and maybe use my low-level code generation framework.
My repository is here. The expression tree library is procyon-expressions.
Are there any Java API(s) which will provide plural form of English words (e.g. cacti for cactus)?
Check Evo Inflector which implements English pluralization algorithm based on Damian Conway paper "An Algorithmic Approach to English Pluralization".
The library is tested against data from Wiktionary and reports 100% success rate for 1000 most used English words and 70% success rate for all the words listed in Wiktionary.
If you want even more accuracy you can take Wiktionary dump and parse it to create the database of singular to plural mappings. Take into account that due to the open nature of Wiktionary some data there might by incorrect.
Example Usage:
English.plural("Facility", 1)); // == "Facility"
English.plural("Facility", 2)); // == "Facilities"
jibx-tools provides a convenient pluralizer/depluralizer.
Groovy test:
NameConverter nameTools = new DefaultNameConverter();
assert nameTools.depluralize("apples") == "apple"
nameTools.pluralize("apple") == "apples"
I know there is simple pluralize() function in Ruby on Rails, maybe you could get that through JRuby. The problem really isn't easy, I saw pages of rules on how to pluralize and it wasn't even complete. Some rules are not algorithmic - they depend on stem origin etc. which isn't easily obtained. So you have to decide how perfect you want to be.
considering java, have a look at modeshapes Inflector-Class as member of the package org.modeshape.common.text. Or google for "inflector" and "randall hauch".
Its hard to find this kind of API. rather you need to find out some websservice which can serve your purpose. Check this. I am not sure if this can help you..
(I tried to put word cacti and got cactus somewhere in the response).
If you can harness javascript, I created a lightweight (7.19 KB) javascript for this. Or you could port my script over to Java. Very easy to use:
pluralizer.run('goose') --> 'geese'
pluralizer.run('deer') --> 'deer'
pluralizer.run('can') --> 'cans'
https://github.com/rhroyston/pluralizer-js
BTW: It looks like cacti to cactus is a super special conversion (most ppl are going to say '1 cactus' anyway). Easy to add that if you want to. The source code is easy to read / update.
Wolfram|Alpha return a list of inflection forms for a given word.
See this as an example:
http://www.wolframalpha.com/input/?i=word+cactus+inflected+forms
And here is their API:
http://products.wolframalpha.com/api/
I worked the last 5 days to understand how unification algorithm works in Prolog .
Now ,I want to implement such algorithm in Java ..
I thought maybe best way is to manipulate the string and decompose its parts using some datastructure such as Stacks ..
to make it clear :
suppose user inputs is:
a(X,c(d,X)) = a(2,c(d,Y)).
I already take it as one string and split it into two strings (Expression1 and 2 ).
now, how can I know if the next char(s) is Variable or constants or etc.. ,
I can do it by nested if but it seems to me not good solution ..
I tried to use inheritance but the problem still ( how can I know the type of chars being read ?)
First you need to parse the inputs and build expression trees. Then apply Milner's unification algorithm (or some other unification algorithm) to figure out the mapping of variables to constants and expressions.
A really good description of Milner's algorithm may be found in the Dragon Book: "Compilers: Principles, Techniques and Tools" by Aho, Sethi and Ullman. (Milners algorithm can also cope with unification of cyclic graphs, and the Dragon Book presents it as a way to do type inference). By the sounds of it, you could benefit from learning a bit about parsing ... which is also covered by the Dragon Book.
EDIT: Other answers have suggested using a parser generator; e.g. ANTLR. That's good advice, but (judging from your example) your grammar is so simple that you could also get by with using StringTokenizer and a hand-written recursive descent parser. In fact, if you've got the time (and inclination) it is worth implementing the parser both ways as a learning exercise.
It sounds like this problem is more to do with parsing than unification specifically. Using something like ANTLR might help in terms of turning the original string into some kind of tree structure.
(It's not quite clear what you mean by "do it by nested", but if you mean that you're doing something like trying to read an expression, and recursing when meeting each "(", then that's actually one of the right ways to do it -- this is at heart what the code that ANTLR generates for you will do.)
If you are more interested in the mechanics of unifying things than you are in parsing, then one perfectly good way to do this is to construct the internal representation in code directly, and put off the parsing aspect for now. This can get a bit annoying during development, as your Prolog-style statements are now a rather verbose set of Java statements, but it lets you focus on one problem at a time, which is usually helpful.
(If you structure things this way, this should make it straightforward to insert a proper parser later, that will produce the same sort of tree as you have until then been constructing by hand. This will let you attack the two problems separately in a reasonably neat fashion.)
Before you get to do the semantics of the language, you have to convert the text into a form that's easy to operate on. This process is called parsing and the semantic representation is called an abstract syntax tree (AST).
A simple recursive descent parser for Prolog might be hand written, but it's more common to use a parser toolkit such as Rats! or Antlr
In an AST for Prolog, you might have classes for Term, and CompoundTerm, Variable, and Atom are all Terms. Polymorphism allows the arguments to a compound term to be any Term.
Your unification algorithm then becomes unifying the name of any compound term, and recursively unifying the value of each argument of corresponding compound terms.