Contrasting F# and Elm’s record types

Yan Cui

I help clients go faster for less using serverless technologies.

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.

type SimpleRecord = {
Age : int // fields are immutable by default
mutable Name : string // you can optionally allow fields to be mutable
}
// You can define polymorphic functions as field on F# record type too, but it's
// more idiomatic in F# to define them as instance or static methods instead.
// One benefit of doing so is that you don't need to define the generic type
// parameters on your type definition.
type WithPolymorphicFunc<'a, 'b> = {
Id : 'a -> 'b // polymorphic field
}
with
member this.Flip f x y = f y x
let x = { Age = 42; Name = "Boke" }
x.Age // 42
x.Name // Boke
// clone and update
let y = { x with Name = "Spyrion" }
y.Age // 42
y.Name // Spyrion
x.Name // still Boke, since we didn't modify x when we cloned it to create y
x.Name <- "Boke mk 2" // but you can use destructive assignment (<-) to update mutable fields
x.Name // Boke mk 2
let f = { Id = (fun x -> x) }
f.Id 42 // 42
f.Flip (+) "ab" "cd" // "cdab"
// records can be pattern matched
let showAge { Age = age; Name = name } = printf "%s is %d years old" name age
showAge x // Boke mk 2 is 42 years old

 

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).

-- this defines a 'record', i.e. a lightweight labeled data structure
x = { age = 42, name = "Boke" }
-- you can use .label to access the value associated with the labels
x.age -- 42
x.name -- "Boke"
-- you can also use .lable as a function to access the associated value from a record too
.age x -- 42
.name x -- "Boke"
-- clone and update
y = { x | name <- "Spyrion" }
-- you can create type alias for records which gives you better static guarantees
type Character = { age : Int, name : String }
-- but it's generally recommended to define extensible records instead in Elm as it makes
-- your functions more reusable
type Named a = { a | name : String } -- i.e. Named is a record with at least a 'name' field
type Aged a = { a | age : Int }
-- records can be pattern matched
showAge : Character -> String
showAge { age, name } = name ++ " is " ++ (show age) ++ " years old"
showAge x -- Boke is 42 years old
showAge y -- Spyrion is 42 years old
-- however, showAge only works if the input matches the 'shape' of Character exactly, so if
-- you have a record with additional fields then it won't work, e.g.
z = { age = 21, name = "Shady", boss = x }
showAge z -- this gives a type error
-- instead if you leave the input type open then anything goes :-)
showAge2 { age, name } = name ++ " is " ++ (show age) ++ " years old"
showAge2 z -- Shady is 21 years old
-- however, if you want to pattern match against two records with the same fields I haven't
-- found a way to capture the values into different local variables
-- e.g. showAge3 takes two records both with 'name' and 'age' labels
showAge3 { age, name } { age, name } = name ++ " is " ++ (show age) ++ " years old"
showAge3 x y -- Spyrion is 42 years old
-- you can also define polymorphic functions within a record
f = { id x = x, flip f x y = f y x }
f.id 42 -- 42
f.flip (++) "ab" "cd" -- "cdab"

 

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.

-- Extensible Records
-- given a record
x = { age = 42, name = "Boke" }
-- you can clone and remove a field in the process
{ x - age } -- { name = "Boke" }
-- you can also add a field
{ x | species = "Jade Dragon" } -- { age = 42, name = "Boke", species = "Jade Dragon" }
-- you can mix them up
{ x - age | species = "Jade Dragon" } -- { name = "Boke", species = "Jade Dragon" }
-- Composible Record Types
-- given these type aliases for extensible records
type Named a = { a | name : String }
type Aged a = { a | age : Int }
type Species a = { a | species : String }
-- them can be composed together
boke : Named(Aged(Species {}))
boke = { name = "Boke", age = 42, species = "Jade Dragon" }
-- same goes to functions
aboutMe : Named(Aged(Species {})) -> String
aboutMe { age, name, species } = name ++ " is a " ++ species ++ " at " ++ (show age) ++ " years of age"
aboutMe boke -- Boke is a Jade Dragon at 42 years of age
-- type aliases defined using this syntax can still be composed as the inner most part
type NPC = { name : String, age : int }
spyrion : Species(NPC)
spyrion = { name = "Spyrion", age = 42, species = "Ruby Dragon" }
-- similarly you can just defined bespoke labels too
shady : Named(Species { age : Int })
shady = { name = "Shady", age = 21, species = "Goblin" }
-- Structural Typing
-- this function can take any record that has a name field
whoAmI { name } = "My name is " ++ name

 

Related Readings

F# – Record types vs classes

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

Elm – Extensible Records

Research paper – Extensible records with scoped labels

Whenever you’re ready, here are 3 ways I can help you:

  1. 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.
  2. 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.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

7 thoughts on “Contrasting F# and Elm’s record types”

  1. 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.

  2. Pingback: Elm – functional reactive dreams + missile command | theburningmonk.com

  3. 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!

  4. 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.

  5. Pingback: Year in Review, 2014 | theburningmonk.com

  6. 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.

  7. Thanks for the writeup!

    I’d be nice if Elm supported renaming pattern matched variables like JavaScript destructuring does.

Leave a Comment

Your email address will not be published. Required fields are marked *