Hi, newbie question here, I was wondering why this doesn’t typecheck. Is there a way to define a function which returns records with a guarantee on its fields? Thank you.
The annotation for fn
is saying that it can return any record provided it has a name
and age
field of the correct type. However, this is not the case. The function will always return a particular record, not any record. You can make it type check if you specify that:
fn : () -> PersonLike {}
fn _ =
Person "John" 23
1 Like
Thank you very much. As a follow up, is there a way to
type a function like this?
type alias Person =
{ name : String
, age : Int
}
type alias Alien =
{ name : String
, age : Int
, planet : String
}
type alias PersonLike a =
{ a
| name : String
, age : Int
}
fn : () -> PersonLike ?
fn _ =
if 1 == 1 then
Person "John" 23
else
Alien "John" 230 "Mars"
1 Like
No, The return value of a function need to be a concrete type. I think perhaps that you want to use a custom type here instead.
If it was like you described, how would the caller know to access the planet
field? How would the caller know what kind of thing was returned?
This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.