Functional programming

Rustom Mody rustompmody at gmail.com
Mon Mar 3 10:28:38 EST 2014


On Monday, March 3, 2014 8:31:47 PM UTC+5:30, Chris Angelico wrote:
> On Tue, Mar 4, 2014 at 1:38 AM, Rustom Mody  wrote:
> > If you want the (semantic) equivalent of python's [1,2,'foo']
> > you need to make an explicit union Int and String and its that
> > *single* union type's elements that must go in.
> > In all cases its always a single type. And so
> > sum([1,2,[3])

> Okay. That's how the declaration goes, then. So how do you tell it
> that 1 isn't an Int, it's a member of the union of Int and String? How
> do you create a list which has [Int_String(1), Int_String(2)] and is
> therefore allowed to be added to [Int_String('foo')] ? Can you do that
> with literals?

Mmmm This is getting a bit OT for a python list
Anyway here goes
The Union type is called Either.
Its got two constructors -- Left and Right -- better to think of them as
tags to not confuse with OO constructors.
The names Left and Right seem to be a bit meaningless because the Either
type is completely generic -- any types S and T can be 'unioned' as
Either S T
where the S components look like Left x for x : S
and the T components look like Right x for x : T

So python's [1,2,"foo"] is
written as
[Left 1, Left 2, Right "foo"]

> This is why it's tricky to put rules in based on type inference. The
> programmer's intent isn't in the picture. If Python ever acquires that
> kind of restriction ("here's a list that can contain only this type /
> these types of object"), I would hope that it's left up to the
> programmer, not the compiler, to stipulate. That's how it is with Pike
> (if you just say "array", it can take anything), and that's the only
> way to be sure the programmer doesn't have to fight the language.

> You said earlier

> >> On Tue, Mar 4, 2014 at 1:08 AM, Rustom Mody wrote:
> >> > If 'integer-less-than-3' were a type then yes there would be this
> >> > problem. More generally, if types could overlap then automatic
> >> > type-inference is impossible

> The type "Int" overlaps with the type "Union of Int and String". How
> is that resolved? 

By decreeing "no overlap!" :-)

Left 1 : Either Int String
whereas 1 : Int

Strictly speaking 'union' should be called 'disjoint union' but this is
so universal in programming that its dropped as redundant.

Heck even C's union is disjoint! If we have

union u
{ 
  int i;
  char c;
};

union u x;

Now you cant interchange the usages of x x.i and x.c




More information about the Python-list mailing list