From F# to Scala – type inference

It’s a new year, a new job, a new language (Scala) and runtime (JVM) to work with.

After a week of learning about my new surroundings at Space Ape Games and getting up to speed with Scala I have learnt a fair bit. In my own journey (aided by Twitter’s Scala School, Odersky’s Coursera course and Effective Scala) I found the target audience for a lot of online materials is Java developers, or developers who are new to functional programming.

As a proficient F# developer, a lot of the FP concepts translate quite easily to Scala (albeit with a different, more verbose syntax). However, Scala does have a lot of language features that do not exist in F# and many things (such as type inference) work slightly differently and can bite you in subtle ways if caught unaware of these differences.

So, for anyone coming into Scala from F#, I hope I can provide some useful info based on the things that I found interesting in my journey.

One of those things is how type inference differs in the two languages.

 

F# uses a Hindley-Milner type inference system similar to its ML brethren, but Scala’s type inference works slightly differently.

Take the following example for instance, this bit of code works just fine in F#.

but the same doesn’t work in Scala…

unless you explicitly specify the type parameter for toList.

Interestingly, if you rewrite the function in curried form then the Scala compiler is able to infer the type for toList.

but the order of parameters matters somehow..

which I eventually understood thanks to some helpful folks on Twitter.

 

Although less restrictive, this limitation of only being able to unify types from left to right also applies to F#.

For example, a simple example using the backward pipe (<|) is enough to cause the compiler to bark.

I hope this has been useful for you, over the next weeks or months I should be adding more posts to this series as I better familiarise myself with Scala, both in terms of language features as well as the toolchain/ecosystem around it.

See here for the rest of the series (as they become available).

Year in Review, 2016

Changes, Changes, Changes

On a personal front, 2016 has been a year of great highs and lows.

I left JUST EAT in March, and started working at Yubl where I had the pleasure of working with an amazing group of people and had lots of fun building things with AWS Lambda and Node.js. We took an ailing architecture that was hard to work with and difficult to release (and required downtime to release to production) and transformed it completely in the space of a few months.

The number of production releases went up by more than ten-fold, features were sometimes completed and released into production in a matter of hours. The product was starting to do well and featured by the App Store several times and ranked as high as 4th in the social category.

  

Then everything came to a crushing and disappointing end as funding issues and the reality of a startup reared its ugly head.

What followed was several weeks of job hunting, during which I learnt a lot:

  • London has a vibrant tech scene and there are lots of interesting companies doing amazing things
  • most companies are still weary of the new serverless paradigm, many are “interested” but few are taking the plunge
  • DevOps is super hyped up (and in my opinion, completely misunderstood by most)
  • many companies are buying tickets to the Containerization Train, even though the cheaper, faster and more reliable Serverless Express is right next to it
  • the money available in the contract market is ridiculous
  • there’s a wave of relatively new consultancy firms (EqualExperts, Contino, 101Ways, etc.) that are following the footsteps of ThoughtWorks and doing good things in the Enterprise Consultancy space

After much soul searching, I decided to follow my heart and go back to the games industry. As of tomorrow, I’ll be starting at Space Ape Games studio in Holborn and working with a Scala-based stack.

 

Learning and Sharing

I spoke at 19 conferences and user groups, delivering talks on a diverse range of topics : F#, Serverless, Neo4j, Elm and APL. I have learnt a lot along the way, and visited Dubai and Sydney for the first time and they were both memorable experiences.

I prepared and delivered some new talks this year:

 

I took part in and completed all 25 Advent of Code challenges in F#.

 

Top Posts

 

See you in 2017

That’s it folks, happy new year! Wish you all a very productive 2017 

Advent of Code F# – Day 25

ps. look out for all my other solutions for Advent of Code challenges here.

 

Day 25

See details of the challenge here.

Today’s input looks like this:

cpy a d
cpy 7 c
cpy 362 b
inc d
dec b
jnz b -2

At last, we’re at the end of this year’s Advent of Code challenges, and today’s challenge is another twist of the assembunny code we’ve seen a few times this year, most recently on Day 23.

Ad before, let’s define the instruction set as a union type and make short work of the parsing the input file.

One notable difference to today’s challenge though is that we’re no longer interested in the value of the registers but the output from executing the program.

So instead of returning the registers we’ll use a sequence comprehension to return the output values as an infinite, and lazy sequence instead.

(ps. I initially wrote the execute function with a nested recursive function, but on second thought the problem feels more concisely expressed as a while loop so I rewrote it as such)

To wrap up today’s challenge (part 2 just requires you to click a link to wrap up your AOC journey for another year) we need to find the first value of n that will yield pairs of [ 0, 1 ] indefinitely. Of course you can’t be sure that the pattern repeats indefinitely without deeper understanding of the pattern of change in the register values (perhaps it’d be a better approach rather than the trial-and-error route I have gone with). I have gone with 1000 values all following that pattern = repeating indefinitely, but turns out the answer is the same even when you use Seq.take 10.

So there it is folks, another year and another set of wonderfully enjoyable challenges. With you all a happy new year and see you soon!

 

Links

Advent of Code F# – Day 24

ps. look out for all my other solutions for Advent of Code challenges here.

 

Day 24

See details of the challenge here.

Today’s challenge is a mix of Breadth-First Search (or Level Order Tree Traversal) and the Travelling Salesman Problem.

First, let’s parse the input file into a 2D array to make it easier for us to work with.

My first attempt at solving this challenge with the same BSF approach that has been so useful in this year’s AOC challenges proved unsuccessful. Unlike previous challenges, today’s problem can involve backtracking so we can’t rely on a naive cache of positions we have passed through thus far.

However, we can still use BSF to find out the shortest distance between any two numbered nodes.

From here, we can build up a dictionary of the distance between every pair of numbered nodes and turn this BSF problem into a Travelling Salesman Problem and find the path through all the numbered nodes with the lowest total distance.

Now we can solve part 1 of the challenge with a simple recursive function.

This solution ran in 109ms on my laptop, including the time to build up the distances between pairs of nodes.

 

Part 2

Of course, if you leave the cleaning robot somewhere weird, someone is bound to notice.

What is the fewest number of steps required to start at 0, visit every non-0 number marked on the map at least once, and then return to 0?

A slight twist on part 1, but we can use the same approach as before but simply stipulate that when all numbered nodes have been traversed we also take into account the distance from the last node back to number 0.

This ran in 113ms on my laptop, including the time to build up the distance between pairs of nodes (or, 14ms if reusing the existing pairDistances)

 

Links

Advent of Code F# – Day 23

ps. look out for all my other solutions for Advent of Code challenges here.

 

Day 23

See details of the challenge here.

Today’s input looks like this:

cpy a b
dec b
cpy a d
cpy 0 a
cpy b c
inc a

..

Today’s challenge is an extension to Day 12, where we have introduced a new instruction for toggle (tgl). To make toggling logic simpler let’s introduce a union type to represent the different instructions we can receive and write a function parse them.

Next, let’s add a toggle function to toggle a given instruction and modify the execute function from Day 12 to work with the union type and support the new tgl instruction as well.

Now we can solve part 1.

let part1 = (execute [ “a”, 7 ] inputs).[“a”]

 

Part 2

The safe doesn’t open, but it does make several angry noises to express its frustration.

You’re quite sure your logic is working correctly, so the only other thing is… you check the painting again. As it turns out, colored eggs are still eggs. Now you count 12.

As you run the program with this new input, the prototype computer begins to overheat. You wonder what’s taking so long, and whether the lack of any instruction more powerful than “add one” has anything to do with it. Don’t bunnies usually multiply?

Anyway, what value should actually be sent to the safe?

As the description eludes to, if we use 12 as initial input it might take a while to run.. and the naive approach of just executing the logic as before, ie

let part2 = (execute [ “a”, 12 ] inputs).[“a”]

took a good 4 minutes to run on my 2015 MBP.

If you add a few printfn statements and you’ll a few blocks of instructions that repeat for many cycles, eg.

cpy b c
inc a
dec c
jnz c -2
dec d
jnz d -5

you can add a short-circuit when you see this happen and replace it with the equivalent of a = b * d (as the description eluded to).

 

Links