Hi there!
I’m trying to understand how to use extensible records to do what I want. Here’s a quick example of the situation I’m in:
module Foo exposing (..)
type alias Foo =
{ name : String
}
type alias Selectable a =
{ a
| isSelected : Bool
}
isSelectableSelected : Selectable a -> Bool
isSelectableSelected selectable =
selectable.isSelected
getFooName : Foo -> String
getFooName foo =
foo.name
makeSelectableFoo : Selectable Foo
makeSelectableFoo =
{ name = "Bar"
, isSelected = True
}
getMyFooName =
let
selectableFoo =
makeSelectableFoo
in
getFooName selectableFoo
This does not compile, with the following error:
-- TYPE MISMATCH --------------------------------------------------- src/Foo.elm
The 1st argument to `getFooName` is not what I expect:
37| getFooName selectableFoo
^^^^^^^^^^^^^
This `selectableFoo` value is a:
Selectable Foo
But `getFooName` needs the 1st argument to be:
{ name : String }
Hint: Seems like a record field typo. Maybe isSelected should be name?
Hint: Can more type annotations be added? Type annotations always help me give
more specific messages, and I think they could help a lot in this case!
I’m trying to find a way to write getFooName
in a way that allows me to use it with whichever extended type I choose (Selectable
for instance). As far as this function is concerned, anything with name
property should work out, because all it cares about is whether the argument has the structure of a Foo
(which only has a name).
I understand I could make it work with making a Fooable
type alias and having a bogus “base type”:
module Foo exposing (..)
type alias Bar =
{}
type alias Fooable a =
{ a
| name : String
}
-- ....
getFooName : Fooable a -> String
getFooName foo =
foo.name
makeSelectableFoo : Selectable (Fooable Bar)
makeSelectableFoo =
{ name = "Bar"
, isSelected = True
}
getMyFooName =
let
selectableFoo =
makeSelectableFoo
in
getFooName selectableFoo
This gives me the behaviour I want, but I’ve had to create a bogus empty record type and “Fooable” doesn’t make as much sense as Foo.
How is this type of problem typically solved?