I am in the process of self teaching myself scala.
I know java but I'm having a little problem implementing certain programs with scala.
I am reading a book specifically for learning scala and I'm trying to attempt one of the exercises for expanding my knowledge.
How would you implement this in scala?
I do have some idea on how to start it using Java.
Your help is appreciated.
I think you need something like this:
evalMono(mono: (Double, Double), x:Double) = mono._1 * Math.pow(x, mono._2)
evalPoly(poly: List[(Double, Double), x:Double) = poly.map (item => evalMono(item, x)).sum
Related
I am new to scala. Currently I am trying to develop a calculator as scala project.
But while trying to find the sum I am getting problem. The following code doesn't compile.
def add [T](values :List[T]) : Option[T]={
if (values.isInstanceOf[String]) {
None
}
else if(values.isInstanceOf[Int] || values.isInstanceOf[Long] || values.isInstanceOf[Double]) {
Some(values.sum)
}
}
When you're new to a language, it is important to start slow and discover the abstractions rather than impose them right away without the experience to make it work. I also think it is a bad idea to just rely on standard library functions (unless you are in a hurry) like sum or to look at third-party libraries until you fully understand what the standard library offers.
So in other words, first let's look at ways to solve the problem just for Int:
def add(values: List[Int]) = values.reduce((a, b) => a + b)
The reduce function works because the type of the result matches the type of what is in the list. The contents are Ints, and the sum is an Int. You will also find this can be simplified with some syntactic sugar:
def add(values: List[Int]) = values.reduce(_ + _)
Wait until you see all the ways underscores get used in Scala.
As you keep studying, you will find that in order to accumulate a value that is a different type than what's in the list, you can use one of the fold* methods. But they can work here too, so for example you could also do this:
def add(values: List[Int]) = values.foldLeft(0)(_ + _)
Now try to define the same function for Long, Double, or even String. You will find the implementations will be almost identical.
It's only when you see implementations that look really similar if not identical that you should even think about abstractions. One option to solve this problem is with type classes. They aren't easy for beginners though. Daniel Westheide wrote a great post on the topic, and frankly you would do well to read the whole series as you learn Scala.
I've really simplified things and glossed over a lot of topics (like why foldLeft has two parameter lists with the first one being 0 or what those crazy implicit things are in Daniel's type classes post), but my advice is to be patient and move slowly. Scala isn't easy, but you'll get it.
(But if you are in a hurry and you are a beginner, I think you are better off just using sum and then writing separate functions for each type. This would be an example of what agile author Kenny Rubin would call "necessary" or "unavoidable" technical debt, and that's to be expected from beginners. Just refactor later.)
Or more generic (example with amm):
# import $ivy.`org.typelevel:cats_2.12:0.8.1`
import $ivy.$
# import cats._, cats.implicits._
import cats._, cats.implicits._
# List(1, 2, 3).combineAll
res2: Int = 6
# List("1", "2", "3").combineAll
res3: String = "123"
# List(List(1, 2), List(), List(3)).combineAll
res5: List[Int] = List(1, 2, 3)
Or via fiddle. It works by using the Monoid and Traversable typeclass.
i am studying scala and have been trying to learn as much as i can. After reading the scala programming book i am reading the source code of several projects while trying some examples myself.
I am really struggling to understand what this method does. I understand that this defines a Json value such as type : value or something.
And also it expects a parametrized T that is a subtype of Product (<:), the way it uses the hashtags is completely magic to me. I cannot fathom its meaning.
def jsonFormat1[[#P1 :JF#], T <: Product :ClassManifest](construct: ([#P1#]) => T): RootJsonFormat[T] = {
val Array([#p1#]) = extractFieldNames(classManifest[T])
jsonFormat(construct, [#p1#])
}
Here is the Full Source for the trait, you might need it to fully understand
PS: This example is taken from project spray-json.
I need to write a method that will return the contents of a particular row (index of it is inputted as method parameter). I do not have a huge experience in Scala and therefore I am getting confused. I would do something like a for loop for 1 to 9 if row is not empty return value, however, I have to use recursion and no loops and I am also given this method definitions :
def r(r: Int): Set[Int] = {
//code
}
I also do not know how Set works. Any help would be really appreciated. PS: I am not asking for complete code, an algorithm explanation would be more than enough!
I don't really understand the question. I mean I understand that you are required to use recursion rather than loops (and that's pretty easy), but I don't understand what you are expected to do with that method signature. e.g.
Why is it returning a set?
What does the parameter mean?
What else is in scope that you need to use to solve the problem?
One of the most important parts of leaning to be a programmer is learning to state problems clearly, because often, when the problem is made clear, the solution is obvious.
I wrote and published a Scala Sudoku solver that uses a lot of recursion, but it won't help you here unless you learn some basics.
Functional programming is very different from imperative programming that most people start with when they learn programming. If this is your first functional language, I suggest taking a course like this: https://www.coursera.org/course/progfun. This uses Scala to teach functional language basics, and might help you.
Not able to use loops does not always mean you have to implement a recursive function. There are standard functional constructs like map, filter, and so on, that you can use.
PS: A sudoku solver is what I tried to make when I was starting learning Scala. Here is the code if you want to take a look: https://github.com/saileshmittal/Scadoku.
Here is a Sudoku solver using immutable data structures:
val n = 9
val s = Math.sqrt(n).toInt
type Board = IndexedSeq[IndexedSeq[Int]]
def solve(board: Board, cell: Int = 0): Option[Board] = (cell%n, cell/n) match {
case (r, `n`) => Some(board)
case (r, c) if board(r)(c) > 0 => solve(board, cell + 1)
case (r, c) =>
def cells(i: Int) = Seq(board(r)(i), board(i)(c), board(s*(r/s) + i/s)(s*(c/s) + i%s))
def guess(x: Int) = solve(board.updated(r, board(r).updated(c, x)), cell + 1)
1 to n diff (board.indices flatMap cells) collectFirst Function.unlift(guess)
}
Here is a full usage: https://gist.github.com/pathikrit/a32e17832296befd6b94
I've been learning Scala and decided to play with JSON parsing using json4s. I decided to use XPath syntax for deserializing and came across this strange bit of syntax I've never seen before.
val json = JsonMethods.parse("""{"meaningOfLife": 42}""")
val JInt(x) = json\"meaningOfLife"
The part confusing me is this bit right here
val JInt(x) = ...
I can't wrap my mind around what's happening there, I don't even know how to search this syntax or what it's called. Can anyone help me out? Scala is an amazing language with a lot of neat features that I'm not used to in other languages like C++ and Java.
Edit
To clarify, I'm confused because x isn't defined, but it's somehow being passed into a function or constructor then being assigned to the result of json\"meaningOfLife" which returns a JValue.
Edit 2
After some research and playing around, I figured out that this has something to do with case classes. I was able to run the following code.
case class MyCaseClass (x: Int)
val MyCaseClass(x) = new MyCaseClass(5)
println(x, x.getClass) // prints (5,int)
Which, after looking at some of the code, gives me a good understanding at what's happening.
val MyCaseClass(x) = MyCaseClass(5)
Is extracting (for lack of a better term) the Int value 5 from the instantiated MyCaseClass and storing that into x, meaning x will be of type Int.
In the code for json4s a JInt is a JValue which the \ operator returns. So the JInt(x) is taking out a BigInt (stored in the class JInt) and putting that into the value x from what I gather.
But I still have a question. What is this process called? Is there any documentation on it?
It's called "irrefutable pattern matching" and it's essentially equivalent to this bit of code:
val json = JsonMethods.parse("""{"meaningOfLife": 42}""")
val x = json match {
case JInt(xMatched) => xMatched
}
In other words, any case class or any extractor that fits the pattern of the declaration's left-hand-side can be used in this way.
Addendum:
The "irrefutable" means that a MatchError will be thrown if the pattern cannot be satisfied.
I want to give a Scala presentation and I want to do it by taking an application and evolve it from something which uses java idioms to something that uses the power of scala (traits, pattern matching, implicit convertions, functional programming).
I'm especially interested in something that demonstrates a design change, rather than syntactic sugar. Something where the end scala code is evidently easier to maintain and extend.
So any ideas? (I'm not asking for code examples, just the rough ideas of what example to use and what design principles can be demonstrated).
A wonderful example is developing a little interpreter for a dynamic mini-language.
The basic java implementation requires the classical interpreter design pattern, whereas a functional scala-approach can use many wonderful functional idioms like
case classes
pattern matching
higher-order functions
or maybe even monads in order to produce very clean and easily understandable code.
Just compare
class Number implements Expression {
private int number;
public Number(int number) { this.number = number; }
public int interpret(HashMap<String,Integer> variables) { return number; }
}
with
case NumberLiteral(i) => Integer(i)
See the interpreter examples at the scala page.
To help you choose among the features and build some nice code examples, here are some ideas:
try to stick on your audience business domain. Try to take example (even basics) from their usual applications.
try to guess your audience main language (java, perl, C++) and make syntax comparisons in your examples.
have a look at: A tour of scala and Scala snippets and pick features to preasent, which you like and you are comfortable with.
try to remember your early steps with scala and situations where you were impressed (or puzzled).
I think you may be being too ambitious in your scope. Just showing people a new and unfamiliar syntax is likely to "lose" them a little, so adding in yet more drastic changes may be a step too far. Don't forget: you can always do a second presentation if the first is popular!
I did pretty much this at my company a while back; it was only as I was giving the presentation that I suddenly grasped how strange and incomprehensible some scala syntax was appearing to the audience (or perhaps it was my delivery style!). I found that the following went down well:
An iterative approach - take a single Java method (not a whole program) and then convert to really dumb like-for-like Scala (type declarations and all). Now apply one set of scala substitutions (e.g. type inference), followed by another (e.g. type aliases) followed by another (e.g. closures) etc. The end result of this would probably be about a third of the Java code, much more readable and concise, which can be contrasted as people are now familiar with what is going on. It's amazing to what extent Java is just a jumbled bunch of types and keywords when viewed in comparison with something like scala.
Take a while to explain all the asides - for example, go through pattern-matching in some detail and how it works. Don't skim over extractors or case x :: xs. I found people were really interested in this and what was so great about it!
Functional programming style takes a while to sink in. It's not reasonable to get people to start understanding this stuff straight away. I've been programming in Scala for over a year and I'm still confused by some of it.
Using the REPL is really cool for some low-level things like showing how everything in scala (including synchronized, try-catch etc) is an expression with a type.
When you've justified the awesomeness of the lower-level stuff, hopefully you'll have whetted people's appetite for more. (I was looking at the implementations of the ternary operator with a - scala-familiar - colleague just last week and he found it slightly confusing. Attempting to introduce an entire app to a bunch of newbies is way too much!)
The spelling corrector example was used to explain Python in the Stackoverflow Devdays. A short scala implementation may be a start:
import util.matching.Regex.MatchIterator
val alphabet = 'a' to 'z' toArray
def train(features : MatchIterator) = (Map[String, Int]() /: features)((m, f) => m + ((f, m.getOrElse(f, 0) + 1)))
def words(text : String) = ("[%s]+" format alphabet.mkString).r.findAllIn(text.toLowerCase)
val dict = train(words(io.Source.fromFile("big.txt").mkString))
def edits(s : Seq[(String, String)]) = (for((a,b) <- s; if b.length > 0) yield a + b.substring(1)) ++
(for((a,b) <- s; if b.length > 1) yield a + b(1) + b(0) + b.substring(2)) ++
(for((a,b) <- s; c <- alphabet if b.length > 0) yield a + c + b.substring(1)) ++
(for((a,b) <- s; c <- alphabet) yield a + c + b)
def edits1(word : String) = edits(for(i <- 0 to word.length) yield (word take i, word drop i))
def edits2(word : String) = for(e1 <- edits1(word); e2 <-edits1(e1)) yield e2
def known(words : Seq[String]) = for(w <- words; found <- dict.get(w)) yield w
def or[T](candidates : Seq[T], other : => Seq[T]) = if(candidates.isEmpty) other else candidates
def candidates(word: String) = or(known(List(word)), or(known(edits1(word)), known(edits2(word))))
def correct(word : String) = ((-1, word) /: candidates(word))(
(max, word) => if(dict(word) > max._1) (dict(word), word) else max)._2
List("osters", "musters", "mixters") map correct foreach println
It demonstrates higher order functions, tuple support, regex support, call by name, for expressions. OO features (type system, traits, objects, packages and visibility) are missing. (I aimed at a short implementation.) But you can these to get to a OO implementation. For example you can add some traits like Dictionary, Corrector etc.