Why are these not equivalent?
show $ if someCondition then someInt else some double
and
if someCondition then show someInt else show someDouble
I understand that if you isolate the if ... else
part in the first example to an expression by itself then you can't represent its type with an anonymous sum type, the kind of Int | Double
, like something you could do easily in TypeScript (mentioning TypeScript because it is the langauge I used often and that supports Sum types), and would have to resort to using the Either
data then based on it would call show
.
The example I gave here is trivial but to me it makes more sense to think "Okay we are going to show something, and that something depends on someCondition
" rather than "Okay if someCondition is true then show someInt otherwise show someDouble", and also allows for less code duplication (here the show is repeated twice but it could also be a long function application and instead of an if ... else
there could be >2 branches to consider)
In my mind it should be easy for the compiler to check if each of the types that make the sum type (here Int | Double
) could be used as a parameter to show
function and decides if the types are correct or not. Even better is that show
function always returns a string
no matter the types of the parameters, so the compiler doesn't have to carry with it all the possible "branches" (so all the possible types).
Is it by choice that such a feature doesn't exist? Or is implementing it harder that I think?