Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
Having spent some time this week with Elm I have seen plenty of things to make me like it, a more in-depth review of my experience with Elm so far is in the works but for now I want to talk about Elm’s record type and how it compares with F# record type which us F# folks rely upon so often. At first glance, there are a lot of similarities between the two, but upon closer inspection you’ll find some notable differences.
F#
In F#, to create a record you first have to declare its type, and the idiomatic F# way is to use records as lightweight data containers but you can optionally add ‘members’ (i.e. properties or methods) to your record types too.
Whilst fields are immutable by default, they can be made mutable if you explicitly mark them with the mutable keyword. Whilst this is not an encouraged practice the option is there for you if you need it, usually as an optimization to avoid the GC overhead of using the copy-and-update operation (under the hood F#’s records are compiled to class types so they’re heap allocated and therefore incurs allocation and collection cost), or because you need to interop with C#.
Advantages of using records over classes include the ability to use pattern matching and that they use structural equality semantic. Given their role as lightweight data containers, like tuples, is the sensible choice in most cases but you can still override this behaviour if you need to.
Whilst F# record types can implement interfaces, they cannot be inherited from, a fact that you can argue for or against. Personally I’m on the ‘argue for’ camp as it gives me future guarantee of safety and if I need to support variance I will introduce interfaces and/or use composition instead.
Elm
In Elm, a record can exist on its own without you having to first define a type for it. Defining a type merely creates an alias to help make your code more readable and give you some static safety where it’s needed.
Elm doesn’t have classes but its records allow polymorphic functions to be defined as part of the record. However, these are not the same as F# record’s instance members as there is no this or self keywords in Elm (because Elm’s creators consider it an extremely bad practice to mix data and logic, which I imagine most functional programmers will agree).
Unsurprisingly, Elm’s records can be pattern matched, but one caveat I found is that as far as I can tell there’s no way to capture two records with the same field into two different local variables (see example below).
So far we have seen that Elm’s records are pretty similar to their F# counterparts, where things get interesting is the extensibility options you have with Elm’s records.
Extensible Records
On top of the clone-and-update operations (using the | label <- value syntax) you can also:
- add new fields using the = operator, e.g. { x | species = “Jade Dragon” } adds new species field with the value “Jade Dragon”
- remove fields by using the minus operator, e.g. { x – age } removes the age field from x when cloning
Composible Record Types
Type aliases defined using the { x | label : type } syntax (like Named and Aged in the above example) can be composed together using a somewhat strange syntax, e.g. Name(Aged {}) which says that the record must contain all the fields defined in both Named and Aged. The inner most { } in this case represents an empty record, you can specify bespoke labels and associated types there or use a type alias that is defined using the { label : type } syntax, like the Character type alias we defined in the above example.
Structural Typing
Finally, Elm’s records support structural typing which allows functions to accept any record that has the required fields, this gives you the benefit of dynamic languages.
In F#, whilst you don’t need to explicitly specify the type of the record when pattern matching (e.g. let showName { Name = name } = …), the type inference process will still choose a type for you so you’re statically bound to a particular type. You can, however, support structural typing in a similar way using statically resolved type parameters which also works on normal class types but you lose the ability to use pattern matching in the process, and I always find their syntax a little clumsy so wherever possible I would use interfaces instead.
Related Readings
F# – Referential equality for Record types
F# performance test – structs vs Records
F# – statically resolved type parameters
F# – XmlSerializer, Record types and [CLIMutable]
F# – Serializing F# Record types
AOP – string interning with PostSharp on F# record types
Research paper – Extensible records with scoped labels
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
I’m excited to hear your full review of Elm. It would be fun to program with it – but it would be a steep learning curve for me.
Pingback: Elm – functional reactive dreams + missile command | theburningmonk.com
That’s an interesting point abot the pattern matching with two records. I’m just wondering, why is matching necessary, when you can just use the . operator for record access? I’d just write your function as
showAge3 r1 r2 = r1.name ++ ” is ” ++ (show r1.age) ++ ” years old”
Either way, it’s great to see Elm getting attention from within the F# community!
Of course, you don’t have to use pattern matching and can easily work around limitations like this.
But I think everyone agrees that being able to pattern match against input arguments can make for more self-documenting and readable code, the question here is really whether the current design is the right way to go – it’s convenient and minimalistic but breaks down when field names conflict.
Pingback: Year in Review, 2014 | theburningmonk.com
For anyone who comes across this article, it’s now (as of January 2016) out-of-date with regard to Elm. The latest version of Elm, 0.16, has removed the ability to add or remove fields in records, and has changed the syntax for updating records to look more like F#. Now if you want to update field “foo” on record x, instead of { x | foo <- "bar" }, the Elm syntax is { x | foo = "bar" }. The previous meaning of { x | foo = "bar" }, which meant "add a field named "foo" even if there wasn't one already", has been *removed*. And the { x – foo } syntax, which removed a field named "foo", is also gone.
The rationale, as I understand it, was that this made for far simpler (and faster) code in Javascript, as you could tell the Javascript engine "This object's properties are not going to change", and it could then apply some optimizations to property access. But I don't have a complete grasp of the details.
See https://github.com/elm-lang/elm-platform/blob/master/upgrade-docs/0.16.md for more about the Elm 0.16 upgrade and the new record syntax.
Thanks for the writeup!
I’d be nice if Elm supported renaming pattern matched variables like JavaScript destructuring does.