Combine two functions to create a function with a union type input
38 views
Skip to first unread message
manuel rascioni
unread,
Nov 20, 2016, 4:21:29 PM11/20/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ceylon-users
Hi,
I've wrote this code, in which I combine a function from String to String and another one from Integer to String to create a new function that has input String|Integer and returns a String:
value fn4 = mix(Integer.string, String.uppercased);
print(fn4("ciao"));
print(fn4(160));
Then I tried to generalize it to have generics inputs of the functions:
String(F|S) mix<F, S>(String(F) f, String(S) s) {
return ((F|S arg)
=> switch (arg)
case (is F)
f(arg)
case (is S)
s(arg)
);
}
But (sadly) this piece of code doesn't compiles, saying that cases are not disjoint.
I was wondering why?
Is it because I can't guarantee that F doesn't extends S?
Is there a way to do it?
Gavin King
unread,
Nov 20, 2016, 4:23:19 PM11/20/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ceylon...@googlegroups.com
Right, the issue is that if we have two type parameters, we just can't
be sure that they don't refer to overlapping types. The branches of a
switch are required to be disjoint.
OTOH, the branches of an if statement are *not* required to be
disjoint, so you can use "if (is)" instead of switch.
argument must be assignable to parameter type: 'F|S' is not assignable to 'F'
I'm pretty new to Ceylon, the type system seems very interesting, I'm exploring it :)
John Vasileff
unread,
Nov 20, 2016, 5:45:02 PM11/20/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ceylon...@googlegroups.com
There are actually two ways `is` can be used. The `arg is F` form is just a Boolean expression. The other, `is F arg`, is a condition that will narrow `arg` to the type `F`.