In the "type select on unions" thread, Kyle said:

Longer term I think it could be valuable in looking at changing unions to
> a ML/Haskell/rust style tagged union. Going down this route could help
> with the syntax questions as well. But that is probably a topic for
> another thread.
>

I'd like to kick this discussion off, because I think it's a great idea.
I'll toss out some thoughts on what this might look like in chapel, in the
form of commented code. This is heavily inspired by rust's enum.

// Simple enumerated type
enum Color { Red, Green, Blue }

// (Contrived) sum-of-products type
enum Shape {
  Circle { var radius: real; },
  Rectangle { var length, width: real; },
  Point
}

proc area(s: Shape) {
  select s {
    when Shape.Circle{radius} do return pi * radius**2;
    when Shape.Rectangle{length, width} do return length * width;
    when Shape.Point do return 0;
  }
  // In rust, the field names here need to match the definition;
  // e.g. `when Circle{r} do` would be an error.
  // We could do the same, or we could match based on position,
  // and allow _ for ignored fields, e.g. `when Rectangle{len, _} do`.
  // I prefer the former, to avoid bugs if the enum definition changes.
}

var s = Shape.Rectangle{length:4, width:5};
writeln(area(s));
// Aside: I also like this syntax for record initialization;
// it feels more in-tune with the value semantics.

// Haskell's Maybe type (generic)
enum Maybe {
  Just { var value; },
  Nothing
}
var i: Maybe(int) = parseInt(readString());
select i {
  when Just{value} do writeln("success: ", value);
  when Nothing do writeln("parsing failed");
}

enum Expected {
  Good { var value; },
  Bad { var error: string; }
}
var x: Expected(real) = fallibleComputation();
select x {
  when Good{value} do writeln("success: ", value);
  when Bad{error} do writeln("failed: ", error);
}


Thoughts?

- Sean
------------------------------------------------------------------------------
New Year. New Location. New Benefits. New Data Center in Ashburn, VA.
GigeNET is offering a free month of service with a new server in Ashburn.
Choose from 2 high performing configs, both with 100TB of bandwidth.
Higher redundancy.Lower latency.Increased capacity.Completely compliant.
http://p.sf.net/sfu/gigenet
_______________________________________________
Chapel-developers mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/chapel-developers

Reply via email to