tag:blogger.com,1999:blog-5635961963983713492024-03-14T00:26:51.467-07:00Scala Eye for the Java GuyAnonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.comBlogger50125tag:blogger.com,1999:blog-563596196398371349.post-32800954970890978822015-12-22T23:35:00.000-08:002015-12-22T23:35:43.828-08:00Type Aliases for Functions - Wat?I'm still buried deep in <a href="https://www.manning.com/books/functional-programming-in-scala">Functional Programming Scala</a>. It's an excellent book, but it does have a habit of occasionally introducing new topics a little out of the blue. This morning: Type Aliases.<br />
<br />
It means that when we have something like this:<br />
<br />
<script src="https://gist.github.com/andrewharmellaw/4a42eb6ac1f2db9d502b.js"></script>
And we then make a type alias like this:<br />
<br />
<script src="https://gist.github.com/andrewharmellaw/c14fc3eef9a290e3fec3.js"></script>We can do this:<br />
<br />
<script src="https://gist.github.com/andrewharmellaw/0a6816aad54859abc77e.js"></script>
Woah, what just happened there? Lets rewind. The first clue we need is in the name. Type aliases allow us to give a new name (or an <i>alias</i>, as in "<a href="https://books.google.co.uk/books?id=wak2AAAAQBAJ&pg=PT37&lpg=PT37&dq=braddock+alias+thorne&source=bl&ots=yf0sp9TLS2&sig=AVIHOWbwh0f5LircQZ7oTT0O4Rs&hl=en&sa=X&ved=0ahUKEwimq9PmufHJAhVCAxoKHcrBCm8Q6AEIJTAB#v=onepage&q=braddock%20alias%20thorne&f=false">Braddock alias Thorne</a>" - someone who is known by more than one name) to an existing type. Why? For readability and to save on the typing (the fingers-to-keyboard kind).<br />
<br />
E.g. by defining:<br />
<br />
<script src="https://gist.github.com/andrewharmellaw/68a649c4b953a4e696ee.js"></script>
You can now write <span style="font-family: Courier New, Courier, monospace;">DataTypeMap</span> anywhere in your code that you'd normally write <span style="font-family: Courier New, Courier, monospace;">Map[String. DataTypeAsJson]</span> (thanks to Alvin Alexander for his <a href="http://alvinalexander.com/scala/scala-type-examples-type-aliases-members">notes</a> which I stole this from).<br />
<br />
That's nice and clear, but it doesn't seem to get us all the way to <span style="font-family: Courier New, Courier, monospace;">type Rand[+A] = RNG => (A, RNG)</span>. Why not? The missing piece of the puzzle is down to the fact that here we're aliasing a function type. It's saying that "the <span style="font-family: Courier New, Courier, monospace;">type Rand[+A]</span> is an alias for an action which depends on an <span style="font-family: Courier New, Courier, monospace;">RNG</span> type, and from that it generates a new <span style="font-family: Courier New, Courier, monospace;">A</span> type <i>and</i> returns it in a tuple along with a new <span style="font-family: Courier New, Courier, monospace;">RNG</span> transitioned to the new state." (I paraphrase a little from the description in the book. And to be fair to the authors, they say its a function type later on in the same page. I'm just very slow on the uptake.)<br />
<br />
Lets take this knowledge and scroll back. The <span style="font-family: Courier New, Courier, monospace;">nextInt</span> function is untouched in all of this - we're simply dancing around it with the second, type alias decoration. The third bit is the most interesting.<br />
<br />
So what's happening there? Stepping through it, we can see we're making a new value called (slightly confusingly I'd argue) "<span style="font-family: Courier New, Courier, monospace;">int</span>" of our new type <span style="font-family: Courier New, Courier, monospace;">Rand[Int]</span>. Now remember, in Scala <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2014/01/functions-and-methods-subtle-distinction.html">functions are objects too</a>, and here we're seeing it in action - we're pointing our new val <span style="font-family: Courier New, Courier, monospace;">int</span> at the <span style="font-family: Courier New, Courier, monospace;">nextInt</span> function. With this in mind it makes a lot of sense that the type of <span style="font-family: Courier New, Courier, monospace;">int</span> is a shorthand for <span style="font-family: 'Courier New', Courier, monospace;">RNG => (A, RNG)</span> because it refers to a function (<span style="font-family: Courier New, Courier, monospace;">nextInt</span>) to which you provide an <span style="font-family: Courier New, Courier, monospace;">RNG</span>, and get back a tuple of an <span style="font-family: Courier New, Courier, monospace;">Int</span> and a new <span style="font-family: Courier New, Courier, monospace;">RNG</span> with the state transitioned.<br />
<br />
When you look at it like that, it's actually quite beautiful.<br />
<br />
<h4>
Asides</h4>
<br />
<ul>
<li>The first time I came across type aliases I was even less prepared - there is one in starter code for the first <a href="https://www.coursera.org/course/progfun">Functional Programming in Scala</a> exercise.</li>
<li>Interested in the Haskell equivalent? It seems to me (please ahout if I'm wrong) that Haskell's <a href="http://learnyouahaskell.com/making-our-own-types-and-typeclasses">Type Synonyms</a> are a pretty close parallel.</li>
<li>Want to read more? Twitter's <a href="https://twitter.github.io/effectivescala/#Types and Generics-Type aliases">Effective Scala</a> seems like a good place to start</li>
</ul>
Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-51650148019087784152015-12-03T03:30:00.001-08:002015-12-03T03:30:18.618-08:00Tracing, Step by StepIn this post I want to introduce the simple yet powerful technique of tracing. It's one I'm using more and more to help me get my head around the subtleties of recursion and in the process get a deeper understanding of the factors at play in this type of algorithm.<br />
<br />
We'll take as our first example a piece of code from <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2015/11/the-slow-boat-to-folding.html">my previous post</a> - a call to a function called <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span>:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/279ce12b781f5ea129ae.js"></script></blockquote>
To begin, we next need the internals of this <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> function too:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/5fef78e758793e4041ec.js"></script></blockquote>
With these two pieces of code in hand, we can begin to trace. To do so we ask ourselves, 'what does our starting piece of code become if we replace the call the function, with the elements of the function which will be executed in the call?' So, given this for the first line of our trace:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/279ce12b781f5ea129ae.js"></script></blockquote>
We end up with a second trace line as follows:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/7e205f5daec443c7f362.js"></script></blockquote>
Let's work through this slowly - what happened? It's actually a combination of micro steps. When we make the call, '<span style="font-family: "courier new" , "courier" , monospace;">as</span>' is <span style="font-family: "courier new" , "courier" , monospace;">List(1,2,3)</span>, '<span style="font-family: "courier new" , "courier" , monospace;">b</span>' is <span style="font-family: "courier new" , "courier" , monospace;">0</span>, and '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' is <span style="font-family: "courier new" , "courier" , monospace;">(_ + _)</span>. Consequently, the pattern match will trigger on '<span style="font-family: "courier new" , "courier" , monospace;">case h :: t</span>', and we're left with a new call to <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span>. <br />
<br />
This new <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> call will have parameters based on the application of the right hand side of the <span style="font-family: "courier new" , "courier" , monospace;">case</span> statement:<br />
<blockquote class="tr_bq">
'<span style="font-family: "courier new" , "courier" , monospace;">t</span>' is the <span style="font-family: "courier new" , "courier" , monospace;">tail</span> of the original '<span style="font-family: "courier new" , "courier" , monospace;">as</span>' List (now expressed in terms of '<span style="font-family: "courier new" , "courier" , monospace;">::</span>' (or "Cons") - <span style="font-family: "courier new" , "courier" , monospace;">2 :: 3 :: Nil</span>,<br />
'<span style="font-family: "courier new" , "courier" , monospace;">b</span>' is now the application of the function <span style="font-family: "courier new" , "courier" , monospace;">f</span> to the original value of '<span style="font-family: "courier new" , "courier" , monospace;">b</span>' and the value of the <span style="font-family: "courier new" , "courier" , monospace;">head</span> of '<span style="font-family: "courier new" , "courier" , monospace;">as</span>' - <span style="font-family: "courier new" , "courier" , monospace;">f(0, 1) or (0 + 1)</span>,<br />
and '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' is still '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' - <span style="font-family: "courier new" , "courier" , monospace;">(_ + _)</span></blockquote>
ASIDE: For some (e.g. me as I was learning this technique) this is too big a jump the first time. In this case you can trace out intermediate steps, which will give you:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/c3da6d164d19c6fe5a45.js"></script></blockquote>
Before we continue, applying the technique again on our new <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> input there is an important thing to note (and an illustration of a powerful benefit of the tracing technique). Note on the last line that we've *not* collpased the function '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' - we have '<span style="font-family: "courier new" , "courier" , monospace;">(0 + 1)</span>' rather than '<span style="font-family: "courier new" , "courier" , monospace;">1</span>'. Why not? We have all the information to hand and we could have done the maths and nothing would have broken. The reason we leave it is a convention of tracing - we are aiming simply to reduce all the function calls to their simple equivalents. It is nice to leave the simple elements of a trace <i>explicit</i> until all the calls elsewhere have been made <i>so that</i> you can see the resulting function in the raw, and complete - the one that will be executed when the code runs.<br />
<br />
Lets move on. When we left off, we had another <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> call to trace:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/1a6ae4ce32c27971ec85.js"></script></blockquote>
So lets apply the same logic as last time and see what we get. Again we trigger on the second <span style="font-family: "courier new" , "courier" , monospace;">case</span> statement, giving the following values to the right-hand-side:<br />
<blockquote class="tr_bq">
'<span style="font-family: "courier new" , "courier" , monospace;">t</span>' is the <span style="font-family: "courier new" , "courier" , monospace;">tail</span> of the '<span style="font-family: "courier new" , "courier" , monospace;">as</span>' in the <i>current</i> context - <span style="font-family: "courier new" , "courier" , monospace;">3 :: Nil</span>,<br />
'<span style="font-family: "courier new" , "courier" , monospace;">b</span>' is the application of the function <span style="font-family: "courier new" , "courier" , monospace;">f</span> to the <i>current</i> value of <span style="font-family: "courier new" , "courier" , monospace;">b</span> and the head of '<span style="font-family: "courier new" , "courier" , monospace;">as</span>' - <span style="font-family: "courier new" , "courier" , monospace;">f((0 + 1), 2)</span>, or <span style="font-family: "courier new" , "courier" , monospace;">((0 + 1) + 2)</span>,<br />
and again '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' is still '<span style="font-family: "courier new" , "courier" , monospace;">f</span>' - <span style="font-family: "courier new" , "courier" , monospace;">(_ + _)</span></blockquote>
Mapping this onto the right-hand-side call to <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> gives the <b>next line</b> of trace as follows:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/f4312a486d48da23ab91.js"></script></blockquote>
We need to keep going - we <i>still</i> have a <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> call to expand. We'll not labour the point of this one (its the same as the previous step). Now we have (I've omitted the micro-steps for clarity and brevity):<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/50ed4e32a7cdf5b2eedd.js"></script></blockquote>
This leaves with <i>yet another</i> call to <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span>, but this time we're going to trigger the <b>first</b> <span style="font-family: "courier new" , "courier" , monospace;">case</span> statement. What happens in this circumstance? We forget about everything else, and simply return <span style="font-family: "courier new" , "courier" , monospace;">b</span> - which in our case is '<span style="font-family: "courier new" , "courier" , monospace;">(((0 + 1) + 2) + 3)</span>'. Let's add it to the bottom as usual:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/5210485809546914271a.js"></script></blockquote>
<div>
And with that we've fallen out the bottom of <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> - no more calls, just simple maths. Some people stop here - our result is now clear. Others like to add the final line of the trace as the reslt of this equation. Its kind of up to you. I'm not going to bother to save you scrolling even more, and I don't want to patronise you.<br />
<br />
Given all this, below are some more traces which you can look at to embed this technique fully. I encourage you to do some of your own. It really helps.<br />
<br />
First up is a '<span style="font-family: "courier new" , "courier" , monospace;">product</span>' function which simply calls foldLeft with a multiplicative function.<br />
<br />
Given: <span style="font-family: "courier new" , "courier" , monospace;">def product(l: List[Double]) = foldLeft(l, 1.0) (_ * _)</span><br />
When: <span style="font-family: "courier new" , "courier" , monospace;">product(List(10.0,23.0,96.0))</span><br />
Then:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/5ed778067e2190969b9a.js"></script></blockquote>
Lets move from <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span>s to a <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>. This one is from Functional Programming in Scala:<br />
<br />
Given: <span style="font-family: "courier new" , "courier" , monospace;">def foldRight[A,B](as: List[A], b: B)(f: (A, B) => B): B =</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> as match {</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> case Nil => b</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> case x :: xs => f(x, foldRight(xs, b)(f))</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> }</span><br />
When: <span style="font-family: "courier new" , "courier" , monospace;">foldRight(List(1,2,3), Nil) (List(_,_)) </span><br />
Then:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/860984fee934369834ff.js"></script></blockquote>
Finally here's another <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>. Note that this one is tricksy, due to the slightly unusual higher order function that's used. It's instructive here to see the trace in action. (Note: I've added the function calls but they don't compile. You could fix this by substituting the anonymous function in the example for a named one.)<br />
<br />
Given: <span style="font-family: "courier new" , "courier" , monospace;">def foldRight[A,B](as: List[A], b: B)(f: (A, B) => B): B =</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> as match {</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> case Nil => b</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> case x :: xs => f(x, foldRight(xs, b)(f))</span><br />
<span style="font-family: "courier new" , "courier" , monospace;"> }</span><br />
And: <span style="font-family: "courier new" , "courier" , monospace;">def length[A](as: List[A]): Int = foldRight(as, 0)((_, acc) => acc + 1)</span><br />
When: <span style="font-family: "courier new" , "courier" , monospace;">length(List (5,6,7))</span><br />
Then:<br />
<blockquote class="tr_bq">
<script src="https://gist.github.com/andrewharmellaw/26c550ef747679cfb47b.js"></script></blockquote>
<h3>
Power Tips</h3>
Before we close its worth mentioning a few tips to help you get the most from this learning tool:<br />
<ul>
<li>formatting is your friend - as you can see from the above examples, use spaces liberally to make clear to yourself how things are progressing</li>
<li>so is your IDE - every trace line should parse and compile, and give the same result (though you might have to replace anonymous functions with named ones.)</li>
<li>use this when thinking about execution-time, and tail recursion, and design of your own algorithms - sometimes the functional style can be hard to make the jump to when you're coming from an imperative background. This technique helps <b>significantly</b>. By mapping it out line by line you can check and understand your algorithm, see any potentials problems it has, and see why or why not its tail recursive.</li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-7293031462267996602015-11-18T13:19:00.004-08:002015-11-18T13:22:35.283-08:00The Slow Boat to FoldingI'm back at the Scala-face, working my way through <a href="https://www.manning.com/books/functional-programming-in-scala">Functional Programming in Scala</a> by Paul Chiusano and Rúnar Bjarnason.
<br />
<br />
I'm still taking things slowly. The current task was grokking folding. Why? As Miran Lipovača says in <a href="http://learnyouahaskell.com/higher-order-functions">Learn You A Haskell</a>:
<br />
<blockquote class="tr_bq">
<span style="font-family: inherit;">"<span style="background-color: white; border-image-outset: initial; border-image-repeat: initial; border-image-slice: initial; border-image-source: initial; border-image-width: initial; border: 0px; font-size: 16px; font-weight: bold; line-height: 25px; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline;"><i>Folds can be used to implement any function where you traverse a list once, element by element, and then return something based on that. Whenever you want to traverse a list to return something, chances are you want a fold.</i></span><span style="background-color: white; font-size: 16px; line-height: 25px;"> That's why folds are, along with maps and filters, one of the most useful types of functions in functional programming.</span>"</span> </blockquote>
<blockquote class="tr_bq">
<div style="text-align: right;">
(I've substituted <i>italics</i> for the authors own <b>bold</b> text)
</div>
</blockquote>
My journey to this post has been a circuitous one; false assumptions, based on semantics from my primary idiom (imperative, non-maths-based programming) having led me astray. I know that there's <a href="https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=folding%20in%20scala">a lot out there already about folding in Scala</a> and so I've attempted to avoid repeating that. Instead I've mapped out the steps which eventually helped me wrap my head around things in a way that stuck.
<br />
<br />
<h3>
Why I got confused (part 1) - worrying about "starting at the left or the right and folding it in"</h3>
Before we dive into the "how I grokked it", I think it pays to define why I got confused to begin with. My first mistake was to think about these pair of functions in terms of how they ate collections. I had some bonkers origami-style image in mind: a long-piece of paper, with the function starting at one end and folding it up concertina style, element by element.
<br />
<br />
I know now I shouldn't have bothered. I'd advise you yo do the same because it'll quite possibly be confusing you too. (For starters you're making a new, separate and <i>individual</i> thing from the fold. You're <i>not</i> simply copying the collection, applying a function to each element in turn - that's mapping.)
<br />
<br />
<h3>
Why I got confused (part 2) - worrying about tail recursion</h3>
And while we're in the habit of dropping things, I also eventually found it useful to stop worrying about the design of the algorithm itself; specifically, "was it tail recursive or not?" Why? It's a level of complexity you don't need in our head right now. It certainly clouded my thinking for far too long. So let it go.<br />
<br />
<h3>
Step 1 - Start thinking about associativity</h3>
Now we've freed up all this mental space, what can we put up there in our lovely spacious minds so we can make progress? The first thing is a nice simple picture of associativity.
<br />
<br />
Now, if you're like me, you'll already "know" about this topic - it's one of the standard bits you skim when learning a new programming language right? And you skim it because it's easy and obvious, right? So why am I going to bore you with it now? Because it's going to give us our "right" and "left", that's why.
<br />
<br />
First up is left-associativity. Say we have a sequence of numbers and operators like so:
<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace;">1 - 2 + 3 = ?</span>
</blockquote>
If I ask you to "add that up" you'll reply "simple, it's <span style="font-family: "courier new" , "courier" , monospace;">2</span>". But what happens if we add some parentheses?:
<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace;">1 - (2 + 3) = ?</span>
</blockquote>
You'll then answer, "still simple, it's now <span style="font-family: "courier new" , "courier" , monospace;">-4</span>". So what changed? Why the different answer? Thats because we've changed the <i>order in which you apply the operators</i>. We've monkey-patched the <i>associativity</i>.
<br />
<br />
<h3>
Step 2 - Tackle left-associativity first</h3>
What we're doing when we don't have any parens (and possibly aren't really thinking about anything like associativity at all) is using <i>left associativity</i> - it's the default in conventional mathematical notation, and the one we learn without realising it in primary school. It applies when two operators have the same precedence (which '<span style="font-family: "courier new" , "courier" , monospace;">+</span>' and '<span style="font-family: "courier new" , "courier" , monospace;">-</span>' do), and tells us that when calculating a sequence of operations of equal precedence we should start at the left hand end of the same-precedence run. <br />
<br />
We can make it explicit with some more parens:
<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace;"><b>((</b>1 - 2<b>)</b> + 3<b>)</b> = 2</span>
</blockquote>
Brilliant. Nice and simple.
<br />
<br />
<h3>
Step 3 - Tackle right-associativity second</h3>
From this, it's easy to guess what this looks like with some explicit, parens-driven <i>right-associativity</i>:
<br />
<blockquote class="tr_bq">
<span style="font-family: "courier new" , "courier" , monospace;"><b>(</b>1 - <b>(</b>2 + 3<b>))</b> = -4</span>
</blockquote>
Nice and simple yet again.<br />
<br />
But look, see how I've bolded the parens? That's the important bit for us as we take the next step. Go on, look at it a little longer - burn it into your retina a wee bit. It helps; trust me.
<br />
<br />
(Note: This has been a ludicrously simplistic overview - if you want to know more, <a href="https://en.wikipedia.org/wiki/Operator_associativity">the wikipedia article</a> is nice and parseable, even for non-maths-heads. Oh, and if I was to write the calculation with proper "right associativity" I'd not need the parens - I'd just write it and say "this is right associative". I put them there however to make us do left-associativity in a "right" way.)
<br />
<br />
<h3>
Step 4(a) - Reduce <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span></h3>
"But wait" I hear you say, "I'm always only adding (or only subtracting) when I <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> / <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>. What does associativity have to do with things?"
<br />
<br />
Let's put this aside for a minute and come back to folding. Taking a hint we just got from associativity, let's tackle <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> first. In the answer to Functional Programming in Scala's question 3.10 it looks something like this:
<br />
<br />
<div>
<script src="https://gist.github.com/andrewharmellaw/f0ca07e468ba205615b6.js"></script>
</div>
We'll now use this function to fold a simple <span style="font-family: "courier new" , "courier" , monospace;">List</span>, tracing the recursive calls one call at a time:
<br />
<br />
<div>
<script src="https://gist.github.com/andrewharmellaw/e2562f2d93352d2e82dd.js"></script>
</div>
What do you see? Look at the parentheses. Do they remind you of anything? Yup, thats it - they look mightily similar to the ones in our previous example in step 2. What we have some here is some explicit left-associativity.
<br />
<br />
(Note: I've just assumed here that you know how to trace. Its a great technique to wrap your head round things in the Functional world. I'm planning on writing a post about it when I get time. For now, just read it line by line - each is equivalent, but just expands the function calls into the bodies of the function that get executed.)<br />
<br />
<h3>
Step 4(b) - Reduce <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span></h3>
Let's crash on; ther's no point hanging around now we have this nugget.<br />
<br />
Here's the simple foldRight from Functional Programming in Scala (listing 3.2) and the associated trace:<br />
<br />
<div>
<script src="https://gist.github.com/andrewharmellaw/af92836315a405efb63f.js"></script>
</div>
The parens should really be jumping out at you now. Notice anything this time? Yup, its the same as the previous example in step 3 - this is exlicit (i.e. parens-driven) right-associativity.
<br />
<br />
<h3>
Step 5 - <i>See</i> the fact you <i>are</i> starting at the left or right end in the reduced output</h3>
Now we're building up a nice bit of "that-makes-sense" momentum lets take the next step.<br />
<br />
Remember is step 1 I advised you forget about the "starting from the left (or right) and folding in" bit? We're now in a position to bring this back into the frame. What might have confused you at the beginning (it confused me anyway) was the fact that the key recursion calls <i>both</i> (<span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> and <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>) start at the head of the <span style="font-family: "courier new" , "courier" , monospace;">List</span> in question and eat their way down to the tail (i.e. both recursively eat away at the collection, one "head" at a time).
<br />
<br />
However, looking back, we now see we can't start collapsing the fold (i.e. start applying the higher-order function, turning it into its result) until we have the <i>innermost</i> pair of values. In the <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> example this is at the left hand side of the traced output, and in <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span> this is at the right hand side. (If you want some corroboration, see where the seed values are placed in step 4 above (the '<span style="font-family: "courier new" , "courier" , monospace;">0</span>' - on the left in the <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span>, and on the right in the <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>.)<br />
<br />
With all this in place, you now have the means to see how this fold calculation is built up, and how, when it reaches it's limit (the end of the collection) it can be collapsed again down to a result.
<br />
<br />
Nice.<br />
<br />
<h3>
Step 6 - See the fact that what is important is why one is trail recursive and one isn't</h3>
Before we close, lets continue to ride the momentum of clarity and see what else we can learn. You may have heard tell of the fact that;<br />
<blockquote class="tr_bq">
"a call is said to be in tail position if the caller does nothing other than return the value of the recursive call" </blockquote>
<blockquote class="tr_bq" style="text-align: right;">
Functional Programming in Scala, Chapter 2, pp.20</blockquote>
What's different is the <i>way </i>the calls are made: <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> does it straight, while <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span> does it as the second parameter to a call to the higher order function. Look; see:<br />
<br />
<div>
<script src="https://gist.github.com/andrewharmellaw/698b8abfa796491a6985.js"></script>
</div>
<br />
If I tell you that <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> is tail-recursive, and <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span> isn't, that should come as no surprise.<br />
<br />
In <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>, we have to apply the function to the result of the recursive call, whereas in <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> we have the result there and then and simply pass it back. This is clearly also the source of the "right" and "left"-ness. The differences in these two expressions is what leads to our parens, and our starting at the right hand end or the left. It suddenly all comes together. <br />
<br />
Taken together it now seems self-evident (to me at least, and hopefully to you if I explained this all clearly enough) how a <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> could compile down into a stack-safe loop, while a <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span> would have to use a stack-imperiling non-tail recursive route.<br />
<br />
<h3>
Bonus Extra Step 9 - The order of the params to fold left and fold right is just convention</h3>
To close, as we're riding the crest of the grok-wave, it's not a bad idea to see what else we can find to slot into our noggins. <br />
<br />
It's not really related to this post apart from the fact that it's to do with fold functions (and we're now in a position to full appreciate it) but how about the order of the params in Haskell's <span style="font-family: "courier new" , "courier" , monospace;">foldLeft</span> and <span style="font-family: "courier new" , "courier" , monospace;">foldRight</span>? <br />
<br />
You'll notice if you look it up that the position of the accumulator param differs. It'd be insulting to point out that the order of params in a function doesn't generally matter, so why is this the case? Let's let Miran Lipovača explain again:<br />
<blockquote class="tr_bq">
"<span style="background-color: white; font-family: "arial" , sans-serif; font-size: 14px; line-height: 25px;">the left fold's binary function has the accumulator as the first parameter and the current value as the second one</span><span style="background-color: white; font-family: "arial" , sans-serif; font-size: 14px; line-height: 25px;">, the right fold's binary function has the current value as the first parameter and the accumulator as the second one</span><span style="background-color: white; font-family: "arial" , sans-serif; font-size: 14px; line-height: 25px;">. It kind of makes sense that the right fold has the accumulator on the right, because it folds from the right side</span>"</blockquote>
<blockquote class="tr_bq" style="text-align: right;">
from <a href="http://learnyouahaskell.com/higher-order-functions">Learn You A Haskell</a></blockquote>
Lovely.Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-826058139752041462014-01-17T12:10:00.001-08:002014-01-17T12:10:08.172-08:00Classes in Scala - Beyond the (Java) Expected<p>There is a lot more power to the Scala type system than any other language I know, and I’ve yet to come across - let along understand – most of it. (I’ve tried a few times now to compose a post on this topic, but realised each time I was still <em>way</em> off being in a position to do so.) However, in my latest reading of <a href="http://horstmann.com/scala/">Scala for the Impatient</a>, I’ve come across some interesting extensions to <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/11/scalas-type-system-mid-learning.html">what I learned</a><strong><em> </em></strong>from <a href="http://www.atomicscala.com">Atomic Scala</a>.</p> <h2>Object-Private Fields</h2> <p>As you’d expect (if you’re coming from Java as I have) methods in a (Scala) class can access private fields of all objects which are derived from that class. But you can also add a more restrictive access flag so that objects can only access private fields of the <em>current</em> object:</p> <blockquote> <p><font face="Courier New">private<strong>[this]</strong> var name // access someObject.name is not allowed</font></p> <p align="right"><font face="ari">example from <a href="http://horstmann.com/scala/">Scala for the Impatient</a> by Cay Horstmann, pp51</font></p></blockquote> <p>Behind the scenes (which I’m beginning to realise is a good way to grok these things) class-private fields have private getters and setters generated for them, whereas object-private fields have neither getters or setters.</p> <p>You can, if you like, even go one step further, replacing “<font face="Courier New">private[this]</font>” with “<font face="Courier New">private[className]</font>". In this case, the field can be accessed only by methods of the named class. Here, the generated code has to generate public getters and setters because the JVM doesn’t support this fine grained level of access control.</p> <h2>Bean Properties</h2> <p>A simple one this. Scala by default creates getters which are simply the same name as the field, and setters which are the name of the field plus “_”. This doesn’t meet the JavaBeans spec, so to <em>also</em> get the expected <font face="Courier New">getFieldName</font> and <font face="Courier New">setFieldName</font> methods you can:</p> <blockquote> <p><font face="Courier New">class Person {<br><strong> @BeanProperty</strong> var name : String = _<br>}</font></p> <p align="right"><font face="ari">example from <a href="http://horstmann.com/scala/">Scala for the Impatient</a> by Cay Horstmann, pp52</font></p></blockquote> <h2>Primary Constructor Parameters</h2> <p>These can use <font face="Courier New">@BeanProperty</font>, <font face="Courier New">private[this]</font> and <font face="Courier New">private[className]</font> forms on top of the “expected” ones.</p> <p>Additionally, if you declare a Primary Class Constructor Parameter without a <font face="Courier New">val</font> or a <font face="Courier New">var</font> form, then how the parameter is processed is dependent upon how you use the field inside the class. In the following, immutable fields <font face="Courier New">name</font> and <font face="Courier New">age</font> are declared and initialised that are object-private:</p> <blockquote> <p><font face="Courier New">class Person(name: String, age: Int) {<br> def description = name + " is " + age + " years old"<br>}</font> <p align="right"><font face="ari">example from <a href="http://horstmann.com/scala/">Scala for the Impatient</a> by Cay Horstmann, pp55</font></p></blockquote> <p>However, if no method uses the parameters they are not saved as fields at all, and they are instead simply treated as parameters that can be accessed within the Primary Constructor and no more.</p> <p>As suggested by Martin Odersky and helpfully repeated by Cay, I found it useful to think of Scala classes as being able to take parameters just like methods do. That makes perfect sense to me.</p> <p>Before we move on, a final word on making a Primary Constructor private:</p> <blockquote> <p><font face="Courier New">class Person <strong>private</strong>(val id: Int) { ... }</font></p> <p align="right"><font face="ari">example from <a href="http://horstmann.com/scala/">Scala for the Impatient</a> by Cay Horstmann, pp57</font></p></blockquote> <p align="left">Lovely for enforcing builders etc, and also just like in Java. Bosh!</p> <h2>Nested Classes</h2> <p>In our final topic, again, Scala seems hyper-flexible. Anything (pretty much) can go inside anything else (functions within functions for examples) and it’s no surprise to find out that classes can go within other classes. I won’t lift the whole example from Cay’s book here (it’s in the free section, go and look at the bottom of page 57) but the important thing to note is that <em>instances</em> have their own classes, just like instances have their own fields too. That is to say, two nested classes of two different instances of the containing class, are two <em>different classes.</em></p> <p>It sounds a little counter intuitive at first, but once you have a play with it it makes more and more sense. However, if you do want to have things as you’d expect from a Java perspective, you can always stick the nested class definition in the companion object (which, you’ll recall is shared across all instances of a class). Or (and this pushed me out of my comfort-zone significantly, you can use a <em>type projection</em>, but I’ll not go into that here. I get the impression that once I get to things like that then I’ll really be moving towards the domain of advanced Scala consumer.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-55326568774539690052014-01-08T11:48:00.001-08:002014-01-08T11:48:33.478-08:00Weighing filter & map Against for’s guards and yield<p>On the surface, it seems that a combination of <font face="Courier New">filter</font> and <font face="Courier New">map</font> can achieve the same end as a <font face="Courier New">for</font>-comprehension with judicious use of guards (e.g. <font face="Courier New">if</font>-expressions) and <font face="Courier New">yield</font>. Or to say the same thing in code:</p> <blockquote> <p><font face="Courier New">b.filter(_ % 2 == 0).map(2 * _)</font></p></blockquote> <p><font face="ari">takes the same inputs and produces the same outputs (with the same lack of side effects) as:</font></p> <blockquote> <p><font face="Courier New">for (elem <- b if (b % 2 == 0)) yield 2 * elem</font></p></blockquote> <p><a href="https://twitter.com/cayhorstmann">Cay Horstmann</a> (for it is from his book, <a href="http://horstmann.com/scala/">Scala for the Impatient</a> that this code and the jumping-off point for this post is taken) points out that the former is preferred by those more experienced or comfortable with the functional idiom, but what I want to examine for a little while is if there are any other reasons why you would pick one over the other.</p> <h2>Legibility</h2> <p>Lets kick off with my old drum, and consider how clean and clear to the eye and comprehending mind they both are. If I’m being honest, in the example above, the f<font face="Courier New">ilter</font>/<font face="Courier New">map</font> combo has it hands down. Just as the method calls chain, so does your understanding as you follow it through, from left to right. With the <font face="Courier New">for</font> on the other hand, you need to either ignore the <font face="Courier New">elem <- b</font><font face="ari">, jump to the guard to get an image of what <font face="Courier New">elem</font> is, before jumping back to the right again to the yield. A lot of work for such a simple piece of logic.</font></p> <p>It also helps greatly that (now I have a good mental construct for <font face="Courier New">map</font>) that we can <em>read</em> the method names and immediately call to mind what is happening. In the <font face="Courier New">for </font><font face="ari">version there are no such explicit semantic clues to latch onto.</font></p> <h2>Flexibility</h2> <p>So far it’s a resounding 1-0 in favour of <font face="Courier New">filter</font> and <font face="Courier New">map</font>, but lets redress the balance. The example we’ve used so far is an incredibly simple one. What if we needed to have two generators?</p> <blockquote> <p><font face="Courier New">for (i <- 1 to 3; j <- 1 to 3) ...</font></p></blockquote> <p>Simple. However our <font face="Courier New">filter</font> and <font face="Courier New">map</font> combo can’t compete because here we’re calling methods which need to be on single object instances. There is nothing available to us which can produce the same effect as simply (I’m sure you could get all complicated, but there’s nothing which will have the “just what I expected” feel of this common <font face="Courier New">for </font>element.</p> <p>Before we move on, we out to kick it up another notch and mention yield expressions can get pretty powerful too (note this example was lazily and brazenly stolen from <a href="http://www.atomicscala.com">Atomic Scala</a> by <a href="http://twitter.com/bruceeckel">Bruce Eckel</a> and <a href="http://twitter.com/dmarsh">Dianne Marsh</a>):</p> <blockquote> <p><font face="Courier New">def yielding3(v:Vector[Int]) : Vector[Int] = {<br> for {<br> n <- v<br> if n < 10<br> isOdd = (n % 2 != 0)<br> if(isOdd)<br> } yield {<br> val u = n * 10<br> u + 2<br> }<br>}</font></p></blockquote> <p>Here, while it is conceivable that in some circumstances our <font face="Courier New">filter</font> and <font face="Courier New">map</font> combo could achieve something similar, it would likely be at the expense of their legibility (which is worth a lot to my mind).</p> <p>Before we finish this aspect, it’s worth pointing out that <font face="Courier New">for</font>’s multiple guards could be represented easily by chaining the same number of <font face="Courier New">filter</font> calls instead of the single one shown at the top of this post, but that’s not quite enough to tip this one back towards a no-score-draw.</p> <h2>Summary</h2>So, it seems that there are indeed reasons when you would want to use <font face="Courier New">for</font> in preference to <font face="Courier New">filter</font> and <font face="Courier New">map</font><font face="ari">. In all cases it’s when you want to unleash a bit of the generator / <font face="Courier New">yield</font> power beyond the simple simple use case. Seems pretty sensible to me, and a rule-of-thumb I’ll be applying in the future.</font> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-33975990245856840232014-01-08T00:09:00.001-08:002014-01-08T00:09:49.365-08:00Functions and Methods – A Subtle Distinction<p>There are a great many benefits to be learning something like Scala, when you have an educational background like I do. Even small snippets of text can flesh out whole expanses of a conceptual landscape, and not just a Scala-one.</p> <p>Today it is the following lines from <a href="https://twitter.com/cayhorstmann">Cay Horstmann</a>’s <a href="http://horstmann.com/scala/">Scala for the Impatient</a>:</p> <blockquote> <p>“Scala has functions in addition to methods. A method operates on an object, but a function doesn’t. C++ has functions as well, but in Java you imitate them with static methods”</p> <p align="right">from <a href="http://horstmann.com/scala/">Scala for the Impatient</a> by Cay Horstmann, pp 21</p></blockquote> <p>I’ve <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/06/terminology-confusion-functions.html">been here before</a>, but in the mass of words I copied from Wikipedia at that point, this simple distinction was lost on me (it’s there, but implicitly). It’s an important distinction too – a method has an object, a function doesn’t - and another fine conceptual tool which, added to my armoury of subtle distinctions and concepts, should help me get further under the skin of both Scala and other languages.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-73465607665377846782014-01-07T11:19:00.001-08:002014-01-08T00:23:30.859-08:00Back on the Old for-Comprehensions Again – Filters and Guard ConditionsNOTE: There's an update to this post, based on a Google+ comment from <a href="http://codingfrog.wordpress.com/">Chris Phelps</a>. Cheers Chris!<br />
I’m <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/slowly-constructing-pseudo-backus-naur.html">back on</a> Scala’s <span style="font-family: Courier New;">for</span> comprehension construct, courtesy of chapter 2 of <a href="https://twitter.com/cayhorstmann">Cay Horstmann’s</a> “<a href="http://horstmann.com/scala/">Scala for the Impatient</a>”. As you’d expect from a book with such a title, he wastes no time in getting to the point, and after a quick (thou comprehensive) intro to the basic single-generator-and-little-else flavour he’s off into multiple generators:<br />
<blockquote>
<span style="font-family: Courier New;">for (i <- 1 to 3; j <- 1 to 3) <br /> print((10 * i + j) + " ") // Prints 11 12 13 21 22 23 31 32 33</span><br />
<div align="right">
<span style="font-family: arial;">from <a href="http://horstmann.com/scala/">Scala for the Impatient</a>, by Cay Horstmann, pp 20</span></div>
</blockquote>
The generators here are in the first set of parens, and give us the i and j variables which are then used in the body of the loop. All very clear. <br />
Then we’re onto the addition of guard conditions:<br />
<blockquote>
<span style="font-family: Courier New;">for (i <- 1 to 3; j <- 1 to 3 if i != j)</span><span style="font-family: Courier New;"> print((10 * i + j) + " ") // Prints 12 13 21 23 31 32</span><br />
<div align="right">
<span style="font-family: arial;">from <a href="http://horstmann.com/scala/">Scala for the Impatient</a>, by Cay Horstmann, pp20</span></div>
</blockquote>
Now <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/slowly-constructing-pseudo-backus-naur.html">before</a> we had “filters” which seemed to do a similar thing – only continue evaluation of that iteration of the loop if they evaluated to <span style="font-family: Courier New;">true</span> themselves - but filters were applied in the body whereas here the guard condition is found within the generator parens, at least in this example.<br />
A bit of reading ahead soon reveals that these “filters” and “guard conditions” seem to be the same thing, but things just looked different because there are two valid forms of the <span style="font-family: Courier New;">for</span>-comprehension syntax – one with parens and semi-colons (Cay’s way in) and the other with curly braces (the Atomic Scala opener). But before we make any sweeping statements, lets check to make sure. Here’s what happens when we start with a parens-version and convert it to the curly-braces flavour:<br />
<blockquote>
<span style="font-family: Courier New;">for (i <- 1 to 3; from = 4 - i; j <- from to 3)<br /> print((10 * i + j) + " ")<br />// Prints 13 22 23 31 32 33 </span> <br />
<span style="font-family: Courier New;">for { // added a newline and replaced the open-paren with a curly brace<br /> i <- 1 to 3 // added a newline and dropped the semicolon<br /> from = 4 – i // added a newline and dropped the semicolon<br /> j <- from to 3 // added a newline and dropped the semicolon<br />} // added a newline and replaced the close-paren with a curly brace<br />print((10 * i + j) + " ")<br />// Still prints 13 22 23 31 32 33 </span><br />
<div align="right">
<span style="font-family: arial;">adapted from <a href="http://horstmann.com/scala/">Scala for the Impatient</a>, by Cay Horstmann, pp20</span></div>
</blockquote>
<div align="left">
As expected, they are the same. I’m not sure if that added flexibility makes me happy or sad. I can however cope with the different ways of referring to filters/guard-conditions. But wait, there’s no time for emotion, <span style="font-family: Courier New;">yield</span> is about to be introduced.</div>
<div align="left">
And here again another subtlety I wasn’t previously aware of seems to have arisen – without a yield, what we have is called a “for-loop”, but once we’re yielding it’s a “for-comprehension”. However, as I am <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/slowly-constructing-pseudo-backus-naur.html">already aware</a>, yielding creates a collection filled with objects of the type output by the <em>first</em> generator, so it’s swings and roundabouts.</div>
<div align="left">
Update (08/02/2014): <a href="http://codingfrog.wordpress.com/">Chris Phelps</a> (one of my Scala-mentors, for which I'm exceedingly grateful) comments: "<span style="background-color: white; color: #404040; font-family: arial, sans-serif; font-size: 13px; line-height: 18px;">Underneath the syntactic sugar, the "filter" or "guard" actually uses a variant of the filter method (withFilter), so if you thought those filters were related to the filter method, well spotted." </span>Looks like I'm on the right track.</div>
Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-26439263224129018382013-12-13T12:30:00.001-08:002013-12-13T12:30:40.100-08:00Conceptualising map and flatMap<p>This time, we’re got a specially selected guest post from Chris at <a href="http://codingfrog.wordpress.com/">CodingFrog</a>. He’s way further down the Scala-learning path than I am, but that just means this post contains maximal goodness and he’s very kindly offered to share it with us. It certainly furthered my understanding in many areas, and made me want to look more into <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">monads</a>. Take it away sir…</p> <p>In this guest post, I wanted to address a few <font face="ari">thoughts</font> about <font face="Courier New">map</font> and <font face="Courier New">flatMap</font>. A number of types in the standard Scala libraries (so-called "monads", though there's a little more to monads than this - but this is not a monad post) have these helpful methods. Both <font face="Courier New">map</font> and <font face="Courier New">flatMap</font> are higher-order functions, meaning they take functions as arguments and apply these to the type's contents. </p> <p>The first exposure most developers have to the <font face="Courier New">map</font> operation is in the context of a collection type. The <font face="Courier New">map</font> operation on a collection applies a mapping function to all the contents of the collection. Given a collection, for example a list, and a function, the function is applied to each element in the collection and a new collection made up of the results is returned. The mapping function takes a single argument, of the same type (or a supertype) of the collection contents, and returns a result, potentially of another type:</p> <blockquote> <p><font face="Courier New">scala> def myFun(x: Int) = x * x</font></p> <p><font face="Courier New">myFun: (x: Int)Int</font></p> <p><font face="Courier New">scala> List(1,2,3) map { myFun }</font></p> <p><font face="Courier New">res0: List[Int] = List(1, 4, 9)</font></p></blockquote> <p>This example shows a named function being passed to <font face="Courier New">map</font>, but of course a lambda could be used as well:</p> <blockquote> <p><font face="Courier New">scala> List(1,2,3) map { x => x * x }</font></p> <p><font face="Courier New">res1: List[Int] = List(1, 4, 9)</font></p></blockquote> <p>We can also use the '<font face="Courier New">_</font>' placeholder, though I personally like to be slightly more explicit with my lambdas to maintain readability. Note that I am also using <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/06/infix-and-postfix-and-prefix.html">infix notation</a><strong><em></em></strong> for <font face="Courier New">map</font> and <font face="Courier New">flatMap</font> in all these examples, but the dotted calling style is perfectly valid as well.</p> <p>Before going further, I'd like to comment on the naming of <font face="Courier New">map</font> and the relationship between the operation and the data type which shares this name. These two uses of “map” are slightly different, but there is a connection. First, the <font face="Courier New">Map</font> data type, as you likely know, is a type which contains key-value pairs. If you think about this slightly differently, this is a conceptual function which "maps" a relationship - given a key input, it produces a value output. The <font face="Courier New">map</font> operation applies a mapping function to values in a collection. You could even pass a <font face="Courier New">Map</font> data type to a <font face="Courier New">map</font> function to convert a collection of keys into a collection of values!:</p> <blockquote> <p><font face="Courier New">scala> val myMap = Map(1 -> 1, 2->4, 3->9)</font></p> <p><font face="Courier New">myMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 4, 3 -> 9)</font></p> <p><font face="Courier New">scala> List(1,2,3) map { myMap }</font></p> <p><font face="Courier New">res2: List[Int] = List(1, 4, 9)</font></p></blockquote> <p>Like <font face="Courier New">map</font>, the first exposure to <font face="Courier New">flatMap</font> is usually in a collection context. Suppose instead of a squaring function that returns a single value, you have a mapping function that returns a list from a given input:</p> <blockquote> <p><font face="Courier New">scala> List(1,2,3) map { x => for {</font></p> <p><font face="Courier New"> | y <- 1 to x toList</font></p> <p><font face="Courier New"> | } yield y</font></p> <p><font face="Courier New"> | }</font></p> <p><font face="Courier New">res3: List[List[Int]] = List(List(1), List(1, 2), List(1, 2, 3))</font></p></blockquote> <p>In this case, instead of a simple list <font face="Courier New">List[Int]</font>, we got a nested list <font face="Courier New">List[List[Int]]</font>! This may be what we want, but suppose we wanted to have a simple list. We can "flatten" this nested list, to remove a level of wrapping and give us a single list. <font face="Courier New">flatMap</font> does that for us in one step. So far so good:</p> <blockquote> <p><font face="Courier New">scala> List(1,2,3) flatMap { x => for {</font></p> <p><font face="Courier New"> | y <- 1 to x toList</font></p> <p><font face="Courier New"> | } yield y</font></p> <p><font face="Courier New"> | }</font></p> <p><font face="Courier New">res4: List[Int] = List(1, 1, 2, 1, 2, 3)</font></p></blockquote> <p>So thinking about collections, it seems like we will be using the <font face="Courier New">map</font> operation much more frequently than we use the <font face="Courier New">flatMap</font> operation. After all, we are much more likely to use a function which gives us a single output for an input rather than one that creates nested collections. Again, we will have cases where we DO want that, but they are less common than the straightforward case.</p> <p>But this isn't the case for other <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">monad types</a>. Let's look at the type <font face="Courier New">Try</font>. The <font face="Courier New">Try</font> type is a type which represents an operation that can fail. <font face="Courier New">Try</font> has two values - <font face="Courier New">Success(t)</font> which contains a successful result <font face="Courier New">t</font>; and <font face="Courier New">Failure(ex)</font> which contains an exception. In other words, instead of throwing the exception, we've grabbed it and stuffed it in a box. You don't know until you look in the box whether it contains the Success or the Failure (and you haven't jumped up the call stack to a catch clause). You can find out what is in the box with pattern matching: </p> <blockquote> <p><font face="Courier New">scala> def examine(myTry: Try[Int]): Int = {</font></p> <p><font face="Courier New"> | myTry match {</font></p> <p><font face="Courier New"> | case Success(t) => t</font></p> <p><font face="Courier New"> | case Failure(e) => -1</font></p> <p><font face="Courier New"> | }</font></p> <p><font face="Courier New"> | }</font></p> <p><font face="Courier New">examine: (myTry: scala.util.Try[Int])Int</font></p></blockquote> <p>This is where I started to struggle to adapt my intuition of <font face="Courier New">List</font> <font face="Courier New">map</font> and <font face="Courier New">flatMap</font>, to the <font face="Courier New">Try</font> ideas of <font face="Courier New">map</font> and <font face="Courier New">flatMap</font>. So what would these mean? <font face="Courier New">Map</font> takes a function which takes a value (of type <font face="Courier New">T</font>) and converts it to another value (of type <font face="Courier New">U</font>, which may or may not be the same as type <font face="Courier New">T</font>). Now <font face="Courier New">map</font> on <font face="Courier New">Try</font> has a specific behaviour guarantee: for <font face="Courier New">Success</font> values, it will call the function on the value in the <font face="Courier New">Success</font>, and wrap the result back up in a <font face="Courier New">Try</font>.:</p> <blockquote> <p><font face="Courier New">case Success(t) => Try(f(t)) </font></p></blockquote> <p>For a <font face="Courier New">Failure</font>, it just returns <font face="Courier New">this</font> - in other words, it skips calling the function, and just returns the original failure:</p> <blockquote> <p><font face="Courier New">case Failure(e) => this</font></p></blockquote> <p>But what if our mapping function wants to be able to represent failures? It's not hard to imagine wanting to have a sequence of operations, each of which could throw some exception. The chain will return a value if all operations in the sequence are successful, or else return the first failure. We can do this by using <font face="Courier New">map</font>. In this case, calling <font face="Courier New">map</font> on the first <font face="Courier New">Try</font>, will call the mapping function, which itself returns a <font face="Courier New">Try</font> value, and wrap that in a <font face="Courier New">Try</font> value:</p> <blockquote> <p><font face="Courier New">scala> import scala.util.{Try, Success, Failure}</font></p> <p><font face="Courier New">import scala.util.{Try, Success, Failure}</font></p> <p><font face="Courier New"><br></font></p> <p><font face="Courier New">scala> def dangerOp1(i: Int): Try[Int] = {</font></p> <p><font face="Courier New"> | if (i != 0) Success(i)</font></p> <p><font face="Courier New"> | else Failure(new IllegalArgumentException)</font></p> <p><font face="Courier New"> | }</font></p> <p><font face="Courier New">dangerOp1: (i: Int)scala.util.Try[Int]</font></p> <p><br><font face="Courier New">scala> val myTry = Success(5)</font></p> <p><font face="Courier New">myTry: scala.util.Success[Int] = Success(5)</font></p> <p><font face="Courier New"><br></font></p> <p><font face="Courier New">scala> myTry map { dangerOp1 }</font></p> <p><font face="Courier New">res5: scala.util.Try[scala.util.Try[Int]] = Success(Success(5))</font></p> <p><font face="Courier New"><br></font></p> <p><font face="Courier New">scala> val myTry2 = Failure(new NoSuchElementException)</font></p> <p><font face="Courier New">myTry2: scala.util.Failure[Nothing] = Failure(java.util.NoSuchElementException)</font></p> <p><font face="Courier New"><br></font></p> <p><font face="Courier New">scala> myTry2 map { dangerOp1 }</font></p> <p><font face="Courier New">res6: scala.util.Try[scala.util.Try[Int]] = Failure(java.util.NoSuchElementException)</font></p></blockquote> <p>So we've gone from <font face="Courier New">Try[T]</font> to <font face="Courier New">Try[Try[T]]</font>, just because we wanted to be able to have our mapping function return some exception cases. This could easily get out of hand if we want to keep mapping more and more functions which could return exceptional cases with <font face="Courier New">Try</font>! What can we do?</p> <p>If we look back at our <font face="Courier New">List</font> example, we see that this is really the same case as when our mapping function itself returned a <font face="Courier New">List</font>. There we went from <font face="Courier New">List[T]</font> to <font face="Courier New">List[List[T]]</font>, while here we're going from <font face="Courier New">Try[T]</font> to <font face="Courier New">Try[Try[T]]</font>. Our solution here is the same as it was there: we need to flatten a layer of nesting. We could take our first result, map our function, and then flatten the result, or we could do the map and the flatten in one step:</p> <blockquote> <p><font face="Courier New">scala> myTry flatMap { dangerOp1 }</font></p> <p><font face="Courier New">res7: scala.util.Try[Int] = Success(5)</font></p> <p><font face="Courier New"><br></font></p> <p><font face="Courier New">scala> myTry2 flatMap { dangerOp1 }</font></p> <p><font face="Courier New">res8: scala.util.Try[Int] = Failure(java.util.NoSuchElementException)</font></p></blockquote> <p>Learning <font face="Courier New">map</font> on <font face="Courier New">List</font> gave us this good (or at least, better) intuition for what mapping a higher order function onto that <font face="Courier New">List</font> means. But this didn't give us quite a rich enough intuition of what flatMap means. Applying functions that create <font face="Courier New">lists</font> to members of a <font face="Courier New">list</font> is just not a common enough pattern to really feel it in our bones. Other types, though, will give us the nested construction as our default pattern. It's quite easy, maybe even expected, to run a sequence of steps that each produce exceptions wrapped in <font face="Courier New">Try</font>. A sequence of operations where each one may return an error value wrapped in the <font face="Courier New"><a href="http://www.scala-lang.org/api/current/index.html#scala.Option">Option <font face="ari">monad</font></a></font> seems pretty likely. When we step up to doing asynchronous coding, we can easily envision combining a sequence of operations that will complete in the future, hooking each up to be run in sequence whenever the previous step completes, by using the <font color="#333333" face="Courier New"><a href="http://doc.akka.io/docs/akka/2.0/scala/futures.html">Future monad</a><strong><em></em></strong></font>. In all these cases, <font face="Courier New">flatMap</font> is a much more natural and basic operation than <font face="Courier New">map</font>, which would keep wrapping each step in another level of nesting. By studying <font face="Courier New">map</font> and <font face="Courier New">flatMap</font> in terms of these types, we can get a better intuitve feel for how these operations combine values of these types, rather than falling back to our <font face="Courier New">List</font> intuition of these operations.</p> <p>All of this has nice implications for for-comprehensions, which rely heavily on <font face="Courier New">flatMap</font> internally. But let's leave that for further study, and maybe another post. </p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-87778879582221552872013-12-13T00:09:00.001-08:002013-12-13T00:09:11.881-08:00Even More Legibility Wins (and no Losses) (Part 3 in a Occasional Series): Special “Option” Edition<p>I posted twice before about some of the things in Scala which I think help and hinder legibility – all from my personal perspective of course. Well, here’s the third instalment. It’s dedicated to the <font face="Courier New"><strong><em>Option</em></strong></font>. #winning:</p> <h2>Wins</h2> <ul> <li><font face="Courier New">Option</font> types <ul> <li>just the concept in general – I think it’ll be a long time before I fully grok how great these really are <li>not to mention they’re <em>biased</em> (c.f. Atomic Scala, Atom: “Handling Non-Values with Option”, pp 352) <li>but also their being handled seamlessly in <font face="Courier New">for</font> comprehensions <li>as well as their having <font face="Courier New">foreach</font> and <font face="Courier New">map</font> functions on them <li>and the <font face="Courier New">Option</font> names: <font face="Courier New">Some</font> and <font face="Courier New">None</font></li></ul> <li><font face="Courier New">null</font> (even from Java code) being wrapped as a <font face="Courier New">None</font></li></ul> <h2>Losses</h2> <ul> <li>None – not that I can think of anyway…</li></ul> <h2>Undecided</h2> <ul> <li>The name “Option” – <a href="twitter.com/bruceeckel">Bruce</a> and <a href="twitter.com/dmarsh">Dianne</a> aren’t convinced. I don’t hate it. (c.f. <a href="http://www.atoimicscala.com">Atomic Scala</a>, Atom: “Handling Non-Values with Option”, pp 355)</li></ul> <h2>Post-script</h2> <p>Excitingly, the same idiomatic concept makes it into the Scala equivalent of Java’s <font face="Courier New">try</font>/<font face="Courier New">catch</font>: <font face="Courier New">Try(…)</font> which produces either a <font face="Courier New">Success</font> or a <font face="Courier New">Failure</font><font face="Arial">. Far more on that to come in the next post (and much more), this time from a special guest: Colorado-resident, <a href="http://codingfrog.wordpress.com/">CodingFrog</a>.</font></p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-76386012210475289602013-11-20T00:33:00.001-08:002013-11-20T00:33:48.724-08:00(Many) Legibility Wins and (a few) Losses (Part 2 in an Occasional Series)<p>I <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/legibility-wins-and-losses-part-1-in.html">posted before</a> about some of the things in Scala which I think help and hinder legibility – all from my personal perspective of course. We’ll here’s the next instalment:</p> <h2>Wins</h2> <ul> <li><font face="Courier New">yield</font> <li>“<font face="Courier New">Any</font>” type, and its immediate syb-types <li>Pattern matching with types <li>Pattern matching with tuples <li>rockets (<font face="Courier New"><= <font face="Arial">and</font> =></font>) – so far at least… <li><font face="Courier New">(new Duck).myMethod</font> – to keep the scope of the Duck instance as tight as possible <li>traits – I’ve always liked mixins anyway, but nothing is broken from what I liked in Ruby <li>the terse syntax (sans curly braces etc.) for defining classes when you don’t need it – e.g. “<font face="Courier New">class MyClass</font>” <li><font face="Courier New">val c = new MyObject with MyTrait</font> – when you don’t need to reuse the class definition elsewhere <li><font face="Courier New">sealed</font> – does what it says on the tin <li><font face="Courier New">zip</font> – ditto <li><font face="Courier New">take</font> – ditto <li><font face="Courier New">+</font> – adding a new key-value pair to an existing map. Gives you a new map back <li>catches and pattern matching <li>try blocks being expressions <li>exceptions being only for exceptional circumstances – a nice idiom</li></ul> <h2>Losses</h2> <ul> <li>explicit setter definition <font face="Courier New">(_=) - :$</font> <li>set unions with ‘<font face="Courier New">|</font>’ <li>set differences with ‘<font face="Courier New">&~</font>’ or ‘<font face="Courier New">--</font>‘</li></ul> <h2>Undecided</h2> <ul> <li>no parens for methods which have no side effects – sometimes, when these are abstract, they make you double-take a little</li></ul> <p>Overall, things are getting less and less surprising and more and more #winning. Perhaps my resistance is being worn down. Perhaps I’m just more open to the experience. Or perhaps all this is taking hold. One thing I do know however is that some of the method names on the collections classes are just plain <em>wrong</em>, but I don’t think I’m alone in thinking that.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-34444522722521308232013-11-13T08:28:00.001-08:002014-01-21T04:58:09.767-08:00Scala’s Type System – A Mid-Learning Checkpoint<p>Update (21st January, 2014): There is a subtle error in the section on “Enumerations (by extending Enumeration)”. It’s fixed now.</p> <p>WARNING: THIS POST CONTAINS WAY MORE QUESTIONS THAN ANSWERS</p> <p>ALSO, APOLOGIES IF THE SCOPE OF THIS POST RIDES ROUGH-SHOD OVER THE CANONICAL DEFINITION OF A “TYPE-SYSTEM”. IT SIMPLY CONTAINS EVERYTHING I BRING TO MIND WHEN I THINK ABOUT TYPES IN SCALA OR ANY LANGUAGE. PLEASE FEEL FREE TO POINT OUT MY IDIOSYNCRACIES IN THE COMMENTS</p> <p>You hear statements like “the best thing about Scala is it’s type system” and “Scala has a powerful type system" being flung around a lot. For a long time, it’s been my aim to get a deep enough understanding of this aspect, as the people making this statement (in various forms) are people I respect a great deal.</p> <p>I’ve made some brief forays into this territory before. <a href="http://www.scala-lang.org/api/current/index.html#scala.Option">Option Types</a> is something I’ve heard <a href="https://twitter.com/dickwall">Dick Wall</a> talk about (and also something I think I understand despite not having covered it in my reading yet; thanks Dick) and the <a href="http://typesafe.com/how/training/fasttracktoscala">Fast Track to Scala</a> course introduced me to the core class hierarchy (which seemed infinitely sensible – anything which includes “Any” as a type is clearly trying to strive for something I can relate to). But these and other small aspects I’ve come across haven’t yet enabled me to honestly say I could defend the title of this post.</p> <p>However, this isn’t to say I doubt I will get to this point eventually. Just not yet.</p> <p>To this end, I’ve just been went back over what I’ve learned so far about the type system. It boils down to a set of facts. Lets begin with the ones which shouldn’t be surprising at all to a Java developer, plus a few little bits (signposted with <em>italics</em>) which might raise an eyebrow or produce a smile:</p> <ul> <li>Classes and Objects – instantiate a class to create an object instance. Classes have fields and operations/methods <li>Creating Classes – <em>class bodies are executed when the classes are created</em> <li>Methods inside classes – methods have special access to other class elements (other methods and fields) <li>Fields – <em>Always objects</em>. <em>Can be vals (immutable) or vars (mutable), or functions</em> <li>Class Arguments – like constructors, but a list placed after the class name. <em>Add a val/var to each definition to encapsulate it.</em> You can have varargs too (but remember to put the definition last in the argument list) <li><em>Named and Default Arguments – you can specify the names of, and defaults for, Class arguments. If all args have defaults you can call “new *” without using any parentheses</em> <li>Overloading – methods can be overloaded, as long as the argument lists differ (i.e. the signatures) <li>Constructors – automatically generated for us if we do nothing. The expressions they contain are treated as statements, that is considered purely for their side effects. The result of the final expression is ignored, and the constructed object is returned instead. You can't use return half way through a set of constructor expressions either <li>Auxiliary Constructors – constructor overloading is possible, <em>by defining a method called “this”</em>. All must first call the Primary constructor (which is the constructor produced by the class argument list together with the class body) again using “this”. This means that ultimately, the primary constructor is always called first. Also you can’t use val or var defined arguments, as that would mean the field was only generated by that auxiliary constructor. This guarantees all classes have the same structure <li><em>Case Classes – automatically creates all the fields for you as if you put the val keyword in front of each of them. (You can make the field a var if you like by pre-pending “var” to the definition.) You create them without having to use the “new” keyword. They also provide a nice default toString implementation. You cannot (from Scala 2.10 onwards) inherit from case classes</em> <li>Parameterized Types – at initialisation time, tells the compiler what type of object the container holds <li>Type Inference – don’t bother specifying the type explicitly, you don’t need to <li>Inheritance – inherit from another class using the extends keyword. A derived class can only extend one base class, but a base class can be extended by any number of derived classes <li>Base Class Initialization – Scala guarantees all constructors are called within a class hierarchy during initialisation. If a base class has constructor arguments, then any class that inherits from that base must provide those arguments during construction. Derived-class primary constructors can call any of the overloaded, auxiliary constructors in the base class by providing the necessary constructor arguments in the call. You can’t call base-class constructors inside of overloaded derived-class constructors. The primary constructor is the “gateway” for all the overloaded constructors <li>Overriding Methods – provide an implementation in a derived class of a method in the base class (distinguished by the method signature). <em>The “override” keyword must be provided so Scala knows you intended to override. </em>This gives us polymorphism just as you’d expect from Java. If you want to invoke the base-class version of a method, use the keyword “super” <li>Abstract Classes – like an ordinary class, except that one or more methods <em>or fields</em> is incomplete (i.e. without a definition<em> or initialisation</em>). Signified by the keyword “abstract” before the “class” keyword. Use of “overrides” keyword is optional in definition of abstract methods in concrete subclasses <li>Polymorphism - If we create a class extending another abstract class A <em>along with traits B and C</em>, we can choose to treat that class as if it were only an A <em>or only a B or only a C</em> <li>Composition – just put something inside (i.e. as a field). Typically this is done with one (abstract) class and many traits with definitions but not implementations, deferring this implementation until the concrete base classes are created (aka “delay concreteness”) <li>Type Parameters – like Java Generics, from the perspective of the user <li>Type Parameter Constraints – impose constraints on type parameters (again c.f. Java Generics)</li></ul> <p>So far, so (mostly predictable. Admittedly, there’s some syntactic sugar in it all (another way of thinking about the bits in italics) but there’s nothing to stretch the Java mind too much. But there’s a lot more. The bits which go much further off-piste from a Java perspective (that I’ve come across so far) are as follows:</p> <ul> <li>Functions as Objects – pass them around like any other object, and define methods to take functions as arguments <li>Function Literals – anonymous Functions, frequently only used once. defined by the ‘=>’ symbol. You can even assign an anonymous function to a var or val <li>Pattern Matching with Types – as well as pattern matching against values, you can pattern match against types <li>“Any” Type<strong> – </strong>any type, including functions <li>Pattern Matching with Case Classes – case classes were originally designed for this purpose. When working with case classes, a match expression can even extract the argument fields <li>Enumerations (by extending Enumeration) – a collection of names. Enumeration is typically extended into an object. Within this object we need to define the set of <del>vals assigned to Value (part of Enumeration) that the enumeration represents</del>, <em>enumeration fields and initialize each of them by calling the Enumeration.Value method. Each call to Enumeration.Value returns a new instance of an inner class, also called Value. Furthermore you can</em> <del>and then</del> alias the new enumeration object to the type Value (using the “type” keyword) to allow us to treat as a type. <em>For more information see Cay Hostmann’s “</em><a href="http://horstmann.com/scala/"><em>Scala for the Impatient</em></a><em>”, pp. 65-66.</em> <li>Enumerations (as a Subtype of a Trait) – we can also create something like an Enumeration by using a Tagging Trait. Having taken this leap it doesn’t seem too great a leap to want to do other OO-type things with our Enumeration <li>Tuples – you can return more than one thing from a method, using a nice syntactic sugar to create and access and unpack them. The same unpacking idiom is also accessible to case classes <li>Objects – by using the “object” keyword creates something you can’t create instances of – it already is an instance. That means that “this” still works <li>Companion Objects – associated by having the same name as a class. If you create a field in the companion object, it produces a single piece of data for that field no matter how many instances of the associated class you make. Under the covers, creating a case class automatically creates a companion object with a factory method called “apply”. When you “construct” a new case class without using the “new” keyword Scala is actually calling “apply” (passing in the parameters you provided) and returning a new instance of the class <li>Traits – for assembling small, logical concepts, letting you acquire capabilities piecemeal rather than inheriting as a clump. Ideally they represent a single concept. Defined using the “trait” keyword. Mixed-in to a class by “extends” / “with” keywords (the former if it is the first, and there is no inheritance, the latter for all others). You can mixin as many traits as you like, into concrete or abstract classes. Traits cannot be instantiated on their own. Traits can have values and functions, and be wholly or partially abstract if required (though they don’t have to be). Concrete classes which mixin traits must provide implementations of the abstract elements. Abstract classes which mixin traits need not implement the abstract elements, but the concrete subclasses of them must. Traits can extend from other traits, as well as abstract and concrete classes. If, when you mixin more than one trait, you combine two methods with the same signature (the name plus the type) you can (must) resolve these collisions by hand using super[Type].methodName <li>Tagging Traits – a way of grouping classes or objects together. Sometimes an alternative to Enumerations (combined with case objects). Indicated by the keyword “sealed” which indicates no more subtypes than the ones you see in the current source file <li>Case Objects – like a case class, but an object <li>Type Hierarchy – this is <a href="http://my.safaribooksonline.com/book/programming/scala/9780596801908/the-scala-object-system/scalatypehierarchy">pretty fundamentally different</a> from the one you’ll expect if coming from Java</li></ul> <p>There’s already a lot in what I’ve listed here, and from having used these elements, I can testify to the solid, expressive-but-terse code it lets you write. But from reading ahead a little, and having listened in on conversations between people far brighter than myself, I know this is just the basics. I’ll post back on those more in-depth topics once I come across them.</p> <p>Onward!</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-13452910425859705442013-11-12T02:41:00.001-08:002013-11-12T02:41:22.978-08:00Dianne Marsh Talks About “Demystifying Scala” with Scott Hanselman<p>Just a quick post this, but its been pointed out to me that <a href="http://twitter.com/dmarsh">Dianne Marsh</a> (co-author of <a href="http://www.atomicscala.com/">Atomic Scala</a> and Director of Engineering at <a href="http://www.netflix.com">Netflix</a>) recorded <a href="http://hanselminutes.com/394/demystifying-scala-with-netflixs-dianne-marsh">a recent episode</a> of Scott Hanselman’s <a href="http://hanselminutes.com/">Hanselminutes</a>. In it she talks about demystifying Scala. Definitely worth a listen.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-1658971542454800862013-09-30T12:11:00.001-07:002013-09-30T12:11:58.330-07:00More on the Subtleties of Scala and the Uniform Access Principle<p>I <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/simple-tuples-for-tired-plus-lesson-in.html">posted before</a> about Scala and the <a href="https://en.wikipedia.org/wiki/Uniform_access_principle">Uniform Access Principle</a>. At that point I felt pretty smug that I’d noticed something clever. Well I didn’t realise everything, but luckily the <a href="http://www.atomicscala.com">Atomic Scala</a> Atom: “Uniform Access and Setters” was there to bring me fully up to speed.</p> <p>Once you’ve seen it, it makes perfect sense, but when I came into this chapter-ette, I’d been under the impression thought you could swap <font face="Courier New">def</font>s for <font face="Courier New">val</font>s or <font face="Courier New">var</font>s as you pleased. However, it soon became clear that there was more to think about, and this thinking comes down to contracts; contracts that the language makes with us, and which it (and we) can’t break.</p> <p>For this discussion, the relevant Scala contracts are:</p> <ul> <li><font face="Courier New">val</font>s are immutable <li><font face="Courier New">var</font>s aren’t <li>functions (<font face="Courier New">def</font>) can return different values and so Scala can’t guarantee the result will always be the same</li></ul> <p>This means that you can’t just implement fields and methods from an abstract base type in a subtype using any old variable or function. You must make sure you don’t break the contract that was made already in the parent. Explicitly:</p> <ul> <li>an abstract <font face="Courier New">def</font> can be implemented as a <font face="Courier New">val</font> or a <font face="Courier New">var</font> <li>an abstract <font face="Courier New">var</font> can be implemented as a <font face="Courier New">def</font> as long as a you also provide a setter as well as a getter</li></ul> <p>You’ll note that abstract <font face="Courier New">val</font>s can’t be implemented with <font face="Courier New">def</font>s. That makes sense if we think about it. A <font face="Courier New">def</font> could return various things – Scala can’t guarantee it’ll always be the same (especially if you consider overriding), whereas <font face="Courier New">val</font>s are immutable. Broken contract? Denied.</p> <h2>An Added Subtlety</h2> <p>But wait a minute, we missed a fourth contract. That second bullet mentioned setters. The contracts in play here are actually four-fold:</p> <ul> <li><font face="Courier New">val</font>s are immutable <li><font face="Courier New">var</font>s aren’t <li>functions (<font face="Courier New">def</font>) can return different values and so Scala can’t guarantee the result will always be the same <li><font face="Courier New"><u>vars</u></font><font face="Arial"> require getters and setters</font></li></ul> <p>But we can still roll with that if we add another little piece of Scala sugar, we can supply a setter method in the subtype: </p> <blockquote> <p><font face="Courier New">def d3 = n<br>def d3_=(newVal:Int) = (n = newVal)</font></p></blockquote> <p>Here, the “<font face="Courier New">def d3_=…</font>” line adds the setter Scala needs to fulfil the contracts and we’re back in action.</p> <h2>Does This Also Stand For Non-Abstract Overrides?</h2> <p>One final thing to consider is how uniform really is the Scala implementation of the principle? Pretty well universal as far as I can see, because going beyond the scope of the Atom, what happens when the superclass and it’s methods and fields aren’t abstract? It turns out it’s exactly the same as above, as long as you remember your <font face="Courier New">override</font> keywords. Predictable. Nice.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-78744076754496898212013-09-25T00:32:00.001-07:002013-11-07T07:53:21.207-08:00Scala is an Expression-Based Language Not a Statement-Based OneI listened to a great podcast from the <a href="http://www.mindviewinc.com/Conferences/JavaPosseRoundup/">Java Posse Roundup 2013</a> on the train home last night: “<a href="http://javaposse.com/java-posse-424-roundup-13-functional-programming">Functional Programming</a>”<br />
During it, <a href="http://www.escalatesoft.com/">Dick Wall</a> briefly described how Scala is an “expression-based” language as opposed to a “statement-based” one (because everything in it is an expression) and that this was one of the main reasons why he liked it. <br />
In short:<br />
<ul>
<li>if a language is expression-based, it means everything has a value (i.e. returns something),</li>
<li>but if it is statement-based, some things need to rely on side-effects to work (e.g. in Java if/else doesn’t have a value, it returns <strike>something</strike> nothing)</li>
</ul>
Now, <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/08/statements-and-expressions-via-atomic.html">I’ve looked into the terms statement and expression before</a> on this blog, but the full weight of the concept hadn’t then struck home. Listening to the podcast was the final push I needed. Consequently, I did a little more reading on the topic. I was planning on writing a post here about what I found, but instead found <a href="http://www.joelonsoftware.com/">Joel Spolsky</a> had <a href="http://stackoverflow.com/questions/19132/expression-versus-statement">got there before me</a>.Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-19923450067221166212013-09-23T23:44:00.001-07:002013-09-24T23:57:05.601-07:00Simple Tuples for the Tired, Plus a Lesson in the Uniform Access Principle<p>I’m back on the early train again. I’m tackling Tuples again too. (<a href="http://www.atomicscala.com">Atomic Scala</a>, “Tuples” atom.)</p> <p>I’m after the “Brevity” and “A Question of Style” atoms too, so the more succinct syntax coupled with something my Java-brain isn’t tuned into (plus, I would argue, the early hour) meant I did a quadruple-take and then a little investigation before <em>Tuple unpacking</em> made sense to me. The reason? This idiom (for I’m guessing it’s idiomatic:</p> <blockquote> <p><font face="Courier New">def f = (1, 3.14, “Mouse”, false, “Altitude”)</font></p></blockquote> <p>What do we know from this, despite the spare syntax?</p> <ol> <li>it’s a function (because of the “<font face="Courier New">def</font>”) <li>it’s called “<font face="Courier New">f</font>” <li>it takes no arguments, and does not mutate state (no parentheses just after the method name) <li>it comprises a single expression (no curly braces) <li>the return type is a tuple <li>this return type is <strike>implicit</strike> inferred by the compiler (no need to specify in the method signature) (thanks Semeru-san)</li></ol> <p>With that in mind, what does this function do? Well, nothing. It only serves to make and return a 5-value tuple which can be captured in a val or var; the first element of which is an <font face="Courier New">Int</font>, the second a <font face="Courier New">Double</font>, the third and fifth are <font face="Courier New">String</font>s and the fourth is a <font face="Courier New">Boolean</font><font face="Arial">. In short, it’s a very simple tuple-builder.</font></p> <p>Next step in the atom is to prove to ourselves that a tuple is just a collection of vals. Firstly, we allocate our tuple to a <font face="Courier New">val</font>:</p> <blockquote> <p><font face="Courier New">val (n, d, a, b, h) = f</font></p></blockquote> <p>That’s a little scary to the uninitiated (or tired) too. But it’s simply saying that I want to call the previously defined tuple-maker function, <font face="Courier New">f</font>, and then store the resulting tuple in another, explicitly defined, tuple of vals. This is called <em>unpacking</em>, and that then means, as well as a val for the tuple as a whole, we also have vals for each individual element and can manipulate them individually (notice the order change in the second line, and the “<font face="Courier New">is</font>” function comes from AtomicTest):</p> <blockquote> <p><font face="Courier New">(n, d, a, b, h) is (1,3.14,"Mouse",false,"Altitude")<br>(a, b, n, d, h) is ("Mouse", false, 1, 3.14, "Altitude")</font></p></blockquote> <p>The final little chunk is some tuple indexing. Again, this has an unfamiliar syntax, but makes sense once you roll it around a little:</p> <blockquote> <p><font face="Courier New">f._1 is 1 // NOTE: NOT ZERO-INDEXED!<br>f._2 is 3.14<br>f._3 is "Mouse"<br>f._4 is false<br>f._5 is "Altitude"</font></p></blockquote> <p>This seemed a little haywire at first, but it makes perfect sense. Again, breaking it down, we have <font face="Courier New">f</font>, the tuple-maker function from before, which returns a tuple of elements in a specific order when called. So after the “<font face="Courier New">f</font>” we have a tuple. We can then call methods on this (using the “<font face="Courier New">.</font>” in this example) and the methods we are calling here are the ones for indexing. </p> <h2>Lessons Learned</h2> <ol> <li>Trying to learn a new type of language when still waking up is difficult <li>There is a secret point that this atom is also making: In this simplest of simple functions, <font face="Courier New">f</font>, we seeing the <a href="https://en.wikipedia.org/wiki/Uniform_access_principle">uniform access principle</a> in action. That is to say, as functions are first-class, I should be able to do with a function what I would do with any other object, and it should be transparent. It was this transparency that pulled me up short. Now, having realised this, I’m a lot more comfortable with the principle, and another small piece of Scala syntax</li></ol> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com3tag:blogger.com,1999:blog-563596196398371349.post-90176955906655687572013-09-17T02:06:00.001-07:002013-09-17T02:06:27.364-07:00Slowly Constructing a Pseudo-Backus-Naur Form<p>“For Comprehensions” (or just “Comprehensions”) are famously (on this blog at least) where I “lost it” during the <a href="http://typesafe.com/how/training/fasttracktoscala">TypeSafe’s Fast Track to Scala</a> course <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/05/fast-track-to-scala.html">right back at the start of this</a>, and despite <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/06/deep-breath-for-comprehensions.html">tackling it again on my own</a> via <a href="http://www.manning.com/raychaudhuri/">Scala in Action</a> it’s still not properly stuck. At the time, the “losing it” pretty much felt like I had little familiar to grip onto. Nothing looked as I’d expected it (the syntax for example) and the terminology wrapped around things that were tossed out to help me was alien too. That first post (linked above) already makes clear I’m not coming at Scala from the traditional CompSci background, and in many respects, this unholy combination of factors is precisely why I’m diving into this – I know this is an area I am both weak in, and will benefit greatly from learning. The second post (again linked above), while a lot more positive, still flounders a little in the big-ness of it all. This post is a stripping back, and a bit of solid progress forward too.</p> <h2>The “Comprehensions” Atom</h2> <p>So now I’m tackling them again; the <a href="http://www.atomicscala.com">Atomic Scala</a> <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/09/pattern-matching-take-2-part-1.html">aversion therapy</a> approach has got me up to this point, and I’ve just had my first trip back into the water at the scene where I had my terrible experience last time. But this time I’m prepared. I’ve seen <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/08/the-for-loop-reads-not-sure-aboutssome.html">the basic Scala <u><font face="Courier New">for</font></u> construct on its own</a>, stripped down and simple. I’ve also been steadily introduced to much basic but needed terminology – <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/08/statements-and-expressions-via-atomic.html">“expression” for example</a>, and<strong> “</strong><a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/06/infix-and-postfix-and-prefix.html">infix</a><strong>”</strong> - and built up a solid and dependable understanding of it. Besides this, I’ve slowly jettisoned by must-be-C-like syntax dependence with some hardcore functions-as-objects fiddling and parentheses and semi-colons have been ripped away from me left, right and centre, but I’m still comfortable.</p> <p>But even with all this in the mental kit-bag, I’m going to take this slowly. I’m fortunate that this is also the approach <a href="http://twitter.com/BruceEckel">Bruce</a> and <a href="http://twitter.com/dmarsh">Dianne</a> feel is appropriate. Typically a new concept is introduced not only with the hardcore details, but also with some lighter discussion of why, or how Scala folks mostly tend to use something. They are also very up front about when they’ve avoided looking under such-and-such a rock for now; but they do point out the rocks, so you know there’ll be a return for more at a later date.</p> <p>One such example in this Atom is the discussion around the possible flavours of for-comprehension using either parentheses or curly braces (<a href="http://www.atomicscala.com">Atomic Scala</a>, pp.177). A cursory glance at this topic, considering the (surface) similarity of the Scala for-comprehension with the Java <font face="Courier New">for</font> loop, might indicate that starting an introduction to such significant syntax with surrounding parens rather than curly braces might be more intuitive. It’s not. My biggest mistake was to bring anything of the Java <font face="Courier New">for</font> with me when I started on this Scala construct. By going in first with a multi-line formatting and curly braces at the top and bottom, announcing (subtly) a <em>block</em>, the authors give me something to <em>read, line-by-line</em>. To me, it’s a bonus that this happens to also be the way most Scala code is written.</p> <p>Now that I have the <em><a href="https://en.wikipedia.org/wiki/Metre_(poetry)">metre</a></em> of the construct we’re looking at, I can begin to look at the individual elements. The first step is to re-visit the generator. The statement beginning “the for loop you saw in For Loops was a comprehension with a <em>single generator…” </em>(my<em> italics</em>) implies to the careful reader that things will get harier later on in the generator space - but not yet - we’re sticking with one. I’ve <a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013_08_01_archive.html">already commented</a> that I like this syntax. (And just for the record, I think the Java <font face="Courier New">for</font> syntax, and by extension the C/C++ syntax is terrible.) Lets keep moving.</p> <p>Next up is the addition of some <em>filters</em>. These are expressed in the form of <font face="Courier New">if</font> expressions which I’ve also seen a lot previously. It’s beginning to look as if every element that is pulled out of the input by the generator (or should I say <em>generated</em>?) drops down through the various filters which follow, only proceeding if the expression returns <font face="Courier New">true</font>.</p> <p>The last piece in this puzzle are some <em>definitions</em>. While these aren’t picked out as explicitly as the other two constructs, it seems clear that these are the remaining statements which all seem to be allocating values to vars or vars, either ones which are scoped with in the comprehension body or outwith it. <font face="Courier New">isOdd = (n % 2 != 0)</font> is one such definition. The authors note the lack of val / var declaration for this and I do too. Scala is managing things for us here.</p> <h2>Putting It All Back Together</h2> <p>The final step is to pull it all back together to see what we have in totality – and I’m finding that this is easiest by my building a mini, mental pseudo-<a href="https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form">Backus-Naur Form</a>. (See how nicely formatted my mind is? :D ):</p> <blockquote> <p><font face="Courier New">for ([generator]) {<br> [filter | definition] (*)<br>}</font></p></blockquote> <p><em>Please note, I find B.-N.F. as illegible as anything else, and the above chunk makes no attempt to be valid in any way. (It’s pseudo B.-N. F. remember). But it does provide me a way of representing what I’m building up on the page/screen.</em></p> <p>When we do this it seems clear that we have an incredibly powerful tool for working our ways through collections and filtering each of the elements in turn to restrict things to only the ones we really need, using definitions as required to make our code clean and clear.</p> <h2>But What About <font face="Courier New">yield</font>?</h2> <p>Helpfully for me, this just made sense. Having <a href="http://rubyeyeforthejavaguy.blogspot.co.uk/2007/09/even-more-ruby-surprises-blocks-and.html">come across the same keyword in Ruby</a> (though it’s used differently, with closures) I already had a mental construct of what this keyword should do to a running system that fits use-case just as nicely. Even when we get to the multi-line-block variety Lets add it to the mini-mental pseudo-B.-N. F.:</p> <blockquote> <p><font face="Courier New">for ([generator]) {<br> [filter | definition] (*)<br>} [expression using element from the left-hand-side of the generator | yield] {<br> </font><font face="Courier New">[expression using element from the left-hand-side of the generator] (*)<br>}</font></p></blockquote> <h2>What Next?</h2> <p>I’ve been around this game long enough to know that it’s not going to stay as simple as I currently have it in my head. But this feels nice and solid enough a piece of scaffolding to be getting on with. I’m not going to speculate on where the additional complexity is going to come from. I’m happy for now to roll this elegant piece of syntax around my brain pan for a while and see how it feels.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-68587182402500073072013-09-16T00:25:00.001-07:002013-09-16T00:25:04.923-07:00It’s Nice That…<p>In Scala, Arrays are a lot more similar to other collections classes (like Vector). E.g.:</p> <blockquote> <p><font face="Courier New">def sumIt(args:Int*) = {<br> args.reduce((sum, n) => sum + n)<br>}</font></p></blockquote> <p>Looks pretty similar to:</p> <blockquote> <p><font face="Courier New">def sumIt(args:Vector) = {<br> args.reduce((sum, n) => sum + n)<br>}</font></p></blockquote> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-11685459780697150272013-09-11T13:31:00.001-07:002013-09-11T13:31:26.551-07:00Legibility Wins and Losses (Part 1 in an Occasional Series)<p>I keep banging on about Scala’s syntax and the resulting legibility. I’ve also mentioned more than once that I think the style propounded in <a href="http://www.atomicscala.com">Atomic Scala</a> is the clearest I’ve read anywhere, and is likely to be a deciding factor in the books longevity.</p> <p>What follows is a round-up of the wins, and losses, for legibility, that I’ve encountered so far. this is all opinion, so please feel free to ignore everything in this post.</p> <h2>Wins</h2> <ul> <li>Scripts and classes <li>No semi-colons <li>vals and vars (as well as immutability as a general concept) <li>type inference <li>function definitions <li>The for loop (and how they play with Range literals) <li>Class Arguments <li>Named arguments <li>Default arguments <li>Case Classes (because of the terse syntax – no need for a body!, the removal of the need for “new” and the free “toString”) <li>Some of the methods in core classes (e.g. ‘to’ and ‘until’ when creating Ranges) <li>Overloading <li>String Interpolation <li><em>Optional </em>Parameterized Types (square brackets just seem more apt for a DSL, but being optional means I can avoid using them unless its necessary)</li></ul> <h2>Losses</h2> <ul> <li>:: (aka “prepend to a List”) <li>Some of the methods in the Collections classes (e.g. Vector.sorted) <li>Constructors (where did they go? they’ve just become a “run” of the body of a class. And yes, I know about the “Constructors” Atom in <a href="http://www.atomicscala.com">Atomic Scala</a>) <li>Auxiliary Constructors <li>Function definitions within function definitions <li>“”””bleh””” (triple quotes; really?)</li></ul> <h2>Undecided</h2> <ul> <li>Pattern matchers <li>The Scala Style Guide <li>Optional parentheses <li>Optional ‘.’ when calling methods on objects <li>Return type inferral</li></ul> <p>Could I have a style guide which just banned the “Losses” way of doing things? Yes. We do that in Java all the time. Might I be wrong about some of these? Yes. Noob’s prerogative. Would an IDE help? Yes, syntax highlighting is a boon in my opinion. Have they chipped away at my enthusiasm? Not really. The more I see, the easier it becomes to read. It’s generally getting less and less outlandish looking with every passing day.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-40180807692318689352013-09-11T13:30:00.001-07:002013-09-11T13:30:40.969-07:00Pattern Matching, Take 2, Part 1<p>Things are about to get interesting. I’ve made it to the point in <a href="http://www.atomicscala.com">Atomic Scala</a> where <a href="http://twitter.com/bruckeckel">Bruce (Eckel)</a> and <a href="http://twitter.com/dmarsh">Dianne (Marsh)</a> recommend you jump in if you're proficient in another language (not me, hopefully) or if you didn’t want to make damn certain you grokked the basics, before moving onto the core stuff (definitely me). So what’s up? Pattern Matching that’s what’s up.</p> <p>The first time I came across the Pattern Matching Syntax, like many things in Scala, I wasn’t a fan. I’m rapidly coming to the conclusion however that this initial revulsion is the way things are normally presented, rather than the syntax itself. My primary requirement (in order for it to enter my head and slosh around up there accruing supporting information) is that it <em>reads</em>. That’s one of Dianne and Bruce’s strengths; the first encounters with new syntactical elements always serves as a way to “read it to yourself in your head”. For example, you could narrate their introductory example on pp130 as:</p> <blockquote> <p>“take this <font face="Courier New">color</font> [sic] object and <font face="Courier New">match</font> it to these cases: (<font face="Courier New">{</font>)<br> in the <font face="Courier New">case</font> when it’s <font face="Courier New">“red” =></font> then produce result <font face="Courier New">“RED”<br></font> in the <font face="Courier New">case</font> when it’s <font face="Courier New">“blue” => </font>then produce result <font face="Courier New">“BLUE”</font><br> in the <font face="Courier New">case</font> when it’s <font face="Courier New">“green”</font> => then produce result <font face="Courier New">“GREEN”</font><br> and in the <font face="Courier New">case</font> when it’s anything else (<font face="Courier New">_</font>) <font face="Courier New">=></font> then produce result <font face="Courier New">“UNKNOWN COLOR: ” + color”</font></p></blockquote> <p>That feels right to me. i know it can get a <em>helluva</em> lot more complicated, but to have that basic understanding to hang my hat on helps a lot. Helpfully Bruce and Dianne also signpost specifically where things are going to get hairy later on. But I don’t have to worry about that yet. First I’ve got the exercises to cement things.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-38473210906848831262013-08-26T13:44:00.001-07:002013-09-06T00:28:03.171-07:00The for Loop “Reads”. Not Sure About Some of the Vector Methods Though…<p>The claim that Scala doesn’t “force you to jump through hoops [with the syntax]” (<a href="http://www.atomicscala.com">Atomic Scala</a> pp.109-110) holds true for the for loop, especially when you “read” it as follows:</p> <blockquote> <p><font face="Courier New">// “for i gets each value of the Vector"<br>for (i <- Vector(1, 2, 3, 4)) {<br> println(“the value of I is: “ i)<br>}</font></p></blockquote> <p>I especially like that it parses in this instance, in the same way a lot of Ruby syntax does. (<strong><em>Update, 5th September, 2013</em></strong>: As Summary 2, pp. 126-7 of <a href="http://www.atomicscala.com">Atomic Scala</a> points out, the Scala “<font face="Courier New">for</font>” focusses on the loop, rather than the counting. Precisely. And if you want to count? Loop through a range. Beautifully explicit. You even get the Range’s “<font face="Courier New">to</font>” and “<font face="Courier New">until</font>” methods. Luverly)</p> <p>But what about “<font face="Courier New">Vector.sorted</font>”? I follow the argument (<a href="http://www.atomicscala.com">Atomic Scala</a> pp.110) that Scala likes to “leave things in place” and instead create new copies of things. But for me, a good method name <em>always</em> is, or starts with a verb: <font face="Courier New">getXxxx, sortXxxx, calculateXxxx</font>. That’s because methods <em>act</em> on the object they belong to, using the parameters they are passed.</p> <p>But is this just another thing I’m trying to carry across from the well-worn Java/OO world? My dictionary tells me (we focussed more on creativity at my school…) “sorted” is an adjective, and my dictionary also tells me that an adjective is </p> <blockquote> <p>“a word naming an attribute of a noun", such as sweet” </p> <p align="right">(Oxford Dictionary of English)</p></blockquote> <p>Now if we see it in context:</p> <blockquote> <p><font face="Courier New">val sortedVal = v4.sorted </font></p></blockquote> <p>And read it, knowing that Scala prefers to leave the original objects alone, and return a copy (and in this case a <em>sorted</em> copy) then perhaps I can warm to this. I don’t think I’ll have too much of a problem, as long as things are consistent in this rule. But doesn’t “<font face="Courier New">Vector.sum</font>” already break this rule? (Shouldn’t it be “<font face="Courier New">summed</font>”?)</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-46315581056632983222013-08-26T13:43:00.001-07:002013-08-26T13:43:17.656-07:00Small Things That Make Me Happy #1<p>When you display a Vector:</p> <blockquote> <p><font face="Courier New">val vector = Vector(1, 2, 3)</font></p> <p><font face="Courier New">println(vector) // prints “Vector(1, 2, 3)”</font></p></blockquote> <p>It prints in the same form as the initialization expression.</p> <p>That makes me happy.</p> <p>(from <a href="http://www.atomicscala.com">Atomic Scala</a>, pp.109)</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-90833508260524224132013-08-26T13:42:00.001-07:002013-08-26T13:42:46.929-07:00That’s Annoying<p>Annoyingly, the Scala REPL doesn’t show all the possible completions when you press the [TAB] key. Apparently the <a href="http://docs.scala-lang.org/">Scala documentation</a> may contain other features.</p> <p>I wonder why this is? Something else to add to the “To Find Out” list…</p> <p>Additionally, when running in the REPL, scripts will “sometimes have behaviour that is not proper for regular Scala programs.” (<a href="http://www.atomicscala.com">Atomic Scala</a>, pp 79)</p> <p>…</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-60035195130395264272013-08-26T13:41:00.001-07:002013-08-26T13:41:23.736-07:00Atomic Scala has TDD Baked In<p>I’m still slowly working through <a href="http://twitter.com/BruceEckel">Bruce Eckel</a>’s and <a href="http://twitter.com/dmarsh">Dianne Marsh</a>’s <a href="http://www.atomicscala.com">Atomic Scala</a>. I just got to the Testing "Atom” (Chapter) (pp. 94-100). It’s the first atom (that I can recall anyway) which has merited a sub-atom, entitled “Testing as Part Programming”, and it introduces <strong><em>TDD</em></strong>.</p> <p>I’m a <em>massive</em> fan of TDD, and my this I mean Kent-Beck-Red-Green-Refactor-Test-Driven-<em>Design</em>-TDD, and these guys get it. They keep it simple (it’s a beginners book after all) but it’s the first time I’ve seen TDD being brought in so early to teach a new language (hell, I’ve never even seen it for frameworks outside of Beck’s “<a href="http://www.amazon.co.uk/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530">Test-Driven Development by Example</a>”, and it works excellently. </p> <p>Given the known, but little-discussed <a href="http://blog.gdinwiddie.com/2013/07/23/why-i-practice-tdd/">mental-offloading benefits</a> of TDD, I’m surprised they’re such pathfinders. A real shame really, but others loss is their gain…</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-56836823859629430322013-08-14T07:46:00.003-07:002013-08-14T07:46:34.485-07:00REPL :paste Power Move (via Atomic Scala)<p>This is a blatant cut-and-paste, but as it’s about cutting-and-pasting, I think it’s almost allowed. (from <a href="http://www.atomicscala.com">Atomic Scala</a> by <a href="https://twitter.com/BruceEckel">Bruce Eckel</a> and <a href="https://twitter.com/dmarsh">Dianne Marsh</a>, Summary I, pp. 65)</p> <p>To put the Scala REPL into multi-line, delayed-interpretation, paste-mode, use the <font face="Courier New">:paste</font> command. To evaluate when you’re done, hit CTRL-D.</p> <p>Good times.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0tag:blogger.com,1999:blog-563596196398371349.post-36664010814245773852013-08-14T07:46:00.001-07:002013-08-14T07:46:17.411-07:00Statements and Expressions (via Atomic Scala)<p>NOTE: I’ve posted on the vague area of this topic <em><a href="http://scalaeyeforthejavaguy.blogspot.co.uk/2013/06/terminology-confusion-functions.html">before</a></em>. </p> <p>As previously discussed, not having a strict CompSci background seems to be a particular hindrance when trying to learn Scala. At least when you are following <a href="http://www.amazon.com/Programming-Scala-Comprehensive-Step-Step/dp/0981531644">the</a> <a href="http://www.amazon.com/Scala-Impatient-Cay-S-Horstmann/dp/0321774094/ref=pd_sim_b_2">standard</a> <a href="http://www.amazon.com/Programming-Scala-Scalability-Functional-Objects/dp/0596155956/ref=pd_sim_b_6">texts</a>. One example of this is around the terminology regarding “Statements” and “Expressions”. I know it’s important I know the difference, but what <em>is</em> the difference? “Atomic Scala, Atom: Expressions” (pp. 54) to the rescue:</p> <blockquote> <p>A statement changes state […] An expression expresses [a] result.</p></blockquote> <p>Now, not only is this clear, its <em>terse, </em>and <em>memorable</em> too. I’d expect nothing less from a book co-written by the author of <a href="http://www.mindview.net/Books/TIJ/">Thinking in Java</a>. Good ole’ breezy simplicity. A section of my mind now feels free to really grok the goodness of immutability and case classes.</p> Anonymoushttp://www.blogger.com/profile/15752542489909389878noreply@blogger.com0