Posted by Ilias Van Peer on Wed, 03/22/2017 - 21:23

Optimising the foldl operation in a recursive data structureLet’s start with a some code I plucked from an earlier implementation of an alternative Dict implementation.https://medium.com/media/4c29a6295d5b63a4ae8f60262c55221c/hrefSo, that seems like a fairly straightforward foldl implementation: Recursively execute the operation on the left side, then execute the operation on your own data using the accumulated value from before, then feed that to folding over the right hand side.There’s something here that’s going to make that fairly expensive, though. That last lambda as part of a pipeline, that comes at a cost. How much? Well, let’s come up with an alternative, and see what difference it makes.That lambda could be eliminated if that last line could take the accumulator as its last value. So let’s do some argument shuffling and make a function to flip the 2nd and third arguments of whatever function you pass in.flip2nd : (a -> b -> c -> d) -> a -> c -> b -> dflip2nd f a b c = f a c bUsing this, we can turn that lambda into the following:|> flip2nd foldl op rightAlright, now that we’ve got that, let’s do a quick micro-benchmark to verify this actually helps.https://medium.com/media/2b68f5f5c4713c9f20f18da4f1a300de/hrefResults on my machine.Alright, that’s a fairly large improvement already. Having anonymous functions in a pipeline is probably not a great idea, as far as performance is concerned. It felt more readable with a lambda, though. There has to be a better option. Wait, let’s think about this for a bit. What we’re doing with pipelines, is saying “first compute the lefthand side, then feed that into the right hand side”. We could just as well do that by using a let .. in block, which would at least allow us to remove the flip2nd call.I previously mentioned here that using a let..in expression rather than pipelining would save us the overhead of the right function application operator |> . Turns out that both <| and |> are special cased in the Elm compiler, and a |> b compiles down to b (a)! Big thanks to Richard for pointing that out.Let’s refactor a bit, and compare the result to our previous, optimised result.https://medium.com/media/a13aca4a413b6cb133175781807dd63e/hrefIn case you don’t feel like running them yourself.Alright, that’s another slight performance improvement. Let’s take a step back, and look at an alternative way to desugar the function application operator. a |> b is just sugar for b (a) . No need to store the intermediaries, we can just inline the different parts of the pipeline straight into the final result.https://medium.com/media/1b110e4a45c50d37cffb8c2b85e54d1d/hrefThat yields us another decent little performance improvement. I think that’s all we can do here for now. Let’s stack up the original “pipeline+lambda” version against this “nested/inline” version.Note, also, that readability suffered some, but not too much — I feel like we’ve found a pretty decent balance between legibility and performance, for library code.https://medium.com/media/848a79f24e188f1501ec3ff0cd9f3137/hrefThe final resultsTakeaways:

Optimising for performance in Elm, Pt. 2 was originally published in Ilias Van Peer on Medium, where people are continuing the conversation by highlighting and responding to this story.

Posted by Ilias Van Peer on Wed, 03/22/2017 - 21:20

Part 1: IntroductionFirst, let’s get the obvious disclaimers out of the way.

The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.

— Computer Programming as an Art (1974) - Donald KnuthNow that we’re sure we’re not doing it prematurely…

We follow two rules in the matter of optimization:

1. Don’t do it.2. (for experts only). Don’t do it yet — that is, not until you have a perfectly clear and unoptimized solution.

— Principles of program design (1975) - Michael A JacksonThere, that’s better.Who is this forI’ve written this to document how I went about optimising an alternative Dict type. This type of core functionality needs to be fast, without compromising maintainability. The type of code described here would typically be library code rather than application code.If you find yourself doing such a thing, and need some pointers on how to increase performance, this document may be useful to you.

Don’t write this type of code in regular application code.

Optimise for readability, even to the point of sacrificing performance.MethodologyOptimising for performance in general demands a lot of work and attention to detail. Multiple steps are involved, which I’ll attempt to explain here.1. Identify slow codeThis means using Chrome DevTools (or equivalent) to identify where any slowness if coming from, as well as relying on logic and micro-benchmarks to identify potentially slow code. Beware: identifying slow (Elm) code using Chrome DevTools is not easy, and micro-benchmarks come with a series of pitfalls.The process of using Chrome DevTools to actually identify bottlenecks probably warrants its own series of blogposts.Knowing what goes on behind the scenes is helpful in realising why certain constructs exhibit certain performance characteristics. For this, I recommend Noah’s “Elm compiled documentation” as well as taking a good look at core/Utils.js which holds the code for comparisons, equality and some other interesting little helpers.2. Make it fasterThis is something I’ll try to explain more in-depth in the rest of this series.3. Verify invariants still holdThis is really important.An invariant is something that must hold true about your code. It is a basic assertion you should be able to make before and after calling your function.To explain this with an example, let’s imagine we’re writing a binary search tree (BST). A tree can be modelled by saying that each tree is either the empty node, or a node with a value, a lefthand side and a righthand side.type Tree v = Empty | Node v (Tree v) (Tree v)Now, in order for this tree to be a valid binary search tree, the following invariant must hold:

For each node in the tree, all values on the lefthand side must be strictly smaller and all nodes on the righthand side must be strictly larger than the value of the node itself.

The first step, before attempting to optimise any code that touches the tree — or even before simply writing any code that touches the tree — should be to turn your invariants into executable code. For a binary search tree, that would look roughly like this:https://medium.com/media/bfe9d8252ffcd1197144ef18d7b1805f/hrefNow I can easily set up a number of test-cases, preferably fuzz-tests so I can be sure that it works for random cases rather than the convoluted ones I can come up with myself, to test that my implementation of, say, an insertion algorithm does not break that invariant.Running those tests before and after each change made to some code ensures I don’t slip up and break any guarantees my code is making.4. Benchmark, benchmark and benchmark againChanges that improve performance for some input on one platform, may regress performance for a different type of input, or on a different platform. Setting yourself up with a whole stack of different platforms, browsers and types to test with, is an important part of ensuring that your performance improvement really is, in fact, an improvement at all.The performance of a a > b for example, depends heavily on the type. Some changes will work better for smaller datasets, others on larger datasets. Some changes might result in javascript that might initially perform better, but can’t be handled efficiently by an optimising JIT. Optimising for performance isn’t that clear-cut.Brian Hicks’ excellent elm-benchmark provides you with the tools to run benchmarks, and setting up a series of comparisons with different types and sizes of input is fairly easy.If you’re working on an OSS project, you may wish to apply to BrowserStack or Saucelabs for a free OSS license so you can run your performance tests against hundreds of different platform/browser combinations.5. If there are no regressions, go back to step 1By which I really mean, optimise one step at a time. Quantifying the impact of a change can only be done with that change being regarded in isolation. If you optimise everything at once, then notice a performance regression in a benchmark or an invariant being broken, good luck figuring out what to revert.So, how do I go about step 2, and actually make things faster?Showing patterns that are good candidates for improving performance is, of course, the main point of this series. Now that you’ve wrestled your way through this long introduction, it’s time to get to the good bits. In part 2.

Optimising for performance in Elm, Pt. 1 was originally published in Ilias Van Peer on Medium, where people are continuing the conversation by highlighting and responding to this story.

Posted by Brian Hicks on Mon, 03/06/2017 - 16:00

How do I get JSON out of a port?
Working with ports can be awkward.
You’re really limited as to what values you can send through, so how do you get objects?
Easy: write a JSON Decoder!

Continue Reading

Posted by Brian Hicks on Mon, 03/06/2017 - 16:00

How do I get JSON out of a port?
Working with ports can be awkward.
You’re really limited as to what values you can send through, so how do you get objects?
Easy: write a JSON Decoder!

Continue Reading

Posted by Rundis on Wed, 03/01/2017 - 01:00

Today I’m happy that I can finally announce version 1.0.0 of Elm Bootstrap.
When I set out to develop Elm Bootstrap, my goal was to make an Elm package that
makes it easy to build responsive and reliable web applications in Elm using Twitter Bootstrap. This version is the first step
towards that goal.

docssite

What is it then ?

Elm Bootstrap is a fairly comprehensive library package that wraps the upcoming Twitter Bootstrap 4 CSS framework.
It provides a range of modules and functions to make it pleasant and reasonably typesafe to create a Bootstrap styled
web application in Elm without giving up too much on flexibility. Most of Twitter Bootstrap is opt-in and the same applies to Elm Bootstrap.
That means that you can pick and choose which parts you wish to use for your application.

You will find modules in Elm Bootstrap that corresponds to most of what Twitter Bootstrap refers to as components.
There are no such thing as components in Elm, there are only functions, and functions can be grouped into modules
When I speak about modules you know I’m talking about Elm and when you see components mentioned you know it’s about
Twitter Bootstrap.

These are the main modules that ship with version 1.0.0

  • Layout related
    • Grid - Provides functions to easily create flexbox based responsive grid (rows, columns) layouts.
    • Text - Helper functions for working with text alignment
  • Forms
    • Form, Input, Select, Checkbox, Radio, Textarea and Fieldset - These modules provides functions to create
      nice Bootstrap styled forms with a lot of flexibility
  • Interactive elements
    • Tab, Accordion, Modal, Dropdown and Navbar are modules that provide functions to work with interative elements.
      In Twitter Bootstrap, the corresponding components are backed by JavaScript in Elm Bootstrap it’s all Elm of course.
  • Misc
    • Alert, Badge, Button, Card, Listgroup and Progress provide you functions to create elements that correspond to their Twitter Bootstrap counterpart.

Example of using the Elm Bootstrap Tab module to create an interactive tab control.

Documentation/help

The most comprehensive (and only) application using Elm Bootstrap at the time of writing this is the
user documention site http://elm-bootstrap.info. You can find the source for the site application on github too.
In time this will improve a lot. With the introduction of Ellie we now also
have a great way to share interactive/editable examples of how to use Elm Bootstrap.

If you need help, there is a #elm-bootstrap channel on the Elm slack where you can ask for help.
I’ll try to help when I can and hopefully others can help out there going forward too.

Built on top of Twitter Bootstrap version 4

Twitter Bootstrap is one of the most popular CSS (with some JS) frameworks for building responsive, mobile first web sites.
At the time of writing version 4 is in alpha-6 and apparantly the plan is to move into beta fairly soon.
Version 4 is fully embracing flexbox, which will provide much better control and flexibility.

Creating a wrapper for Twitter Bootstrap probably doesn’t score very high on the hipster scale. However
it’s no denying it’s still very popular and probably will be for some time to come. More importantly I’m using
it in projects and have done so several times in the past, so I know it would be useful to me when I get
a chance to work on an Elm project. Hopefully others will find Elm Bootstrap useful too.

Reasonably type safe you say ?

What’s reasonable is obviously a matter of opinion. But since it’s an Elm package we’re talking about, the
context is that it’s for use in a statically typed language that promotes reliability as a core characteristic.
There is also no denying that Elm doesn’t have the most advanced type system out there. But in my humble opinion it’s
one of the most approachble ones I’ve come across in terms of statically typed functional languages.

There’s no stopping you from just including the CSS from Bootstrap and start using it with the standard Elm Html functions today.
Let’s face it, Twitter Bootstrap is mostly just a whole bunch of classes you apply to relevant elements you compose and voila.
But applying a bunch of class strings is quite error prone, and it’s easy to nest elements incorrectly or apply incorrect classes to
incorrect elements. Trying to alleviate that to some extent is what I’ve been trying to balance with necessary flexibility
when defining the API for Elm Bootstrap.

I’m under no illusions that I’ve found the sweetspot that perfectly balances type safety, flexibility and usability.
But given the constraints (the type system in Elm and my relatively short experience with statically typed functional languages),
I’m reasonably happy with the API as a starting point. Real life use and feedback will surely help it develop
in a direction where more and more people can agree that it really is reasonably type safe !

The development story - aka refactoring galore

For quite some time my main endevaours in Elm has been developing editor support for Elm in Light Table
through my elm-light plugin. I’ve also been working blogging a bit on
my journey learning Elm (and a little Haskell). But in November last year I decided I wanted to dive deeper into Elm, trying to make something
substantial. Ideally something useful, but first and foremost something that would gain me experience in designing an API for use by others in Elm.

The Bootstrap wrapper idea has crossed my mind several times in the past, but never materialized. I did some
research, but couldn’t find anything out there for Elm that was quite as ambitious as I had in mind.

Where to start ?

I first started looking at the very impressive elm-mdl which brings
awesome Google Material Design support to Elm. I got a ton of inspiration from this library.
Next up I had a look through elm-sortable-table, trying to pick
up on good advice and experience for tackling the interactive components in Twitter Bootstrap.

Hmm okay, let’s just start and see where it leads me.

Think, code, refactor ad infinitum

So I started with a couple of modules using a record based api for everthing.
That gave me an API that was pretty type safe and certainly explicit. But it looked horribly verbose
where in many cases it didn’t provide enough value and even in some cases put way to many restrictions on what you could do.
DOH. Back to the drawing board.

I know ! Let’s have 3 list arguments for everything; Options (exposed union types), attributes and children.
So I refactored almost everything (silly I know), but it didn’t really feel right with all those lists and I also started
to get concerned that users would find it confusing with the std Elm Html functions taking 2 lists.
Time to think and refactor again. After that I started to run into cases where I wanted to compose stuff from
several modules, well because stuff is related.

I’ll spare you all the details, but I can’t remember ever having refactored so much code so frequently that I have been during
this process. Doing this in Elm has been an absolute pleasure. Truly fearless refactoring. The kind that is really hard
to explain to other peope who haven’t experienced it. The Elm compiler and I have become the best of buddies during evenings
and nights the past few months.

I can’t remember ever having refactored so much code so frequently that I have been during
this process.

— Magnus Rundberget

Two list arguments

For most elements functions take two list arguments. The first argument is a list of
options, the second is a list of child elements. You create options by calling functions defined in the relevant module.

Pipeline friendly composition

Composition of more complex elements is done by calling pipeline friendly functions. This design gives
a nice balance between type safety and flexibility.

Reaching out to the Elm Community

In the middle/end of January I reached a point where I on one hand was ready to just ship something.
At the same time I was really unsure about what I had created so I reached out for comments on the elm-slack.
Turns out that both Mike Onslow and Richard Feldman both have had overlapping ideas about creating a Bootstrap package for Elm.
We quickly decided to see if we could cooperate in some fashion and decided to hook up on Google Hangout.
Awesome ! We’ve had many really interesting discussions on slack especially related to API design. It’s been really great
to have someone to talk to about these things (other than my analysis paralysis brain).

Going forward

I could have been iterating forever trying to nail the best possible API and/or try to support every bit of Twitter Bootstrap,
but I’ve decided it’s better to just get it out there and get feedback.

The API will certainly get breaking changes going forward, but I don’t see that as such a big negative given
the semantic versioning guarantees and version diffing support provided by the Elm package manager.

I’m hoping folks find this interesting and useful enough to give it a try and give feedback on their
experiences. In the mean time I’m going to work on improving the documentation, test support, API consistency and support for missing
Twitter Bootstrap features.

Posted by Brian Hicks on Mon, 02/27/2017 - 17:00

Introducing elm-benchmark
After the sets series finished, I got really curious…
How fast were these sets, exactly?
I had to shave a lot of yaks to answer that question, but to sum up: Elm now has a benchmarking library!
Let’s take a look at how to use it!

Continue Reading

Posted by Brian Hicks on Mon, 02/27/2017 - 17:00

Introducing elm-benchmark
After the sets series finished, I got really curious…
How fast were these sets, exactly?
I had to shave a lot of yaks to answer that question, but to sum up: Elm now has a benchmarking library!
Let’s take a look at how to use it!

Continue Reading

Posted by wintvelt on Thu, 02/16/2017 - 12:46

Simple helper functions to pipeline nested record updatesContinue reading on Elm shorts »

Posted by wintvelt on Thu, 02/09/2017 - 22:06

3 tricks to get more out of case statementsContinue reading on Elm shorts »

Posted by Brian Hicks on Mon, 02/06/2017 - 11:00

 Wrap-up
Our Set implementation is done!
We just have a few things to wrap up.

Continue Reading

Posted by Brian Hicks on Mon, 02/06/2017 - 11:00

 Wrap-up
Our Set implementation is done!
We just have a few things to wrap up.

Continue Reading

Posted by wintvelt on Wed, 02/01/2017 - 19:02

Free functions, and other useful bitsContinue reading on Elm shorts »

Posted by Brian Hicks on Mon, 01/30/2017 - 17:00

 Map
Now that we have filter and friends, we’re almost done with our Set implementation.
Once we have map, we’ll be done!

Continue Reading

Posted by Brian Hicks on Mon, 01/30/2017 - 17:00

 Map
Now that we have filter and friends, we’re almost done with our Set implementation.
Once we have map, we’ll be done!

Continue Reading

Posted by wintvelt on Wed, 01/25/2017 - 21:02

And how this impacts your users and your codeContinue reading on Elm shorts »