Swift Programming Language

Algebraic Data Types in Swift

11 thoughts
last posted Feb. 8, 2015, 9:19 p.m.
0
get stream as: markdown or atom
0

I also wonder to what extent enums can be used for algebraic data types.

0

Ugh, looks like you can't recurse in enums.

enum Tree {
    case Empty
    case Leaf(Int)
    case Node(Tree, Tree)
}

kills the REPL with a Bus error: 10.

0

This works (as is but not sure if it would work once we start adding other things):

protocol TreeLike {}
enum Tree:TreeLike {
    case Empty
    case Leaf(Int)
    case Node(TreeLike, TreeLike)
}
0
Tree.Node(Tree.Node(Tree.Leaf(1), Tree.Leaf(2)), Tree.Leaf(3))

work with the above definition of Tree.

0

Of course that's fixed to being a Tree of Ints.

enum Tree<T>:TreeLike {
    case Empty
    case Leaf(T)
    case Node(TreeLike, TreeLike)
}

which kills the REPL with:

LLVM ERROR: unimplemented IRGen feature! non-fixed multi-payload enum layout
Assertion failed: (err == 0), function ~Mutex, file /SourceCache/lldb_KLONDIKE/lldb_KLONDIKE-320.3.100/source/Host/common/Mutex.cpp, line 246.
Abort trap: 6

And TreeLike isn't even the suitable generic.

0

The fact these things actually error gives me hope that they're just bugs not intentional limitations of the language.

0

brosner found this:

@jopamer Hey, Swift looks really nice - wondering if enums can have recursive defs: enum Tree<T>{case Leaf(T); case Node(Tree<T>, Tree<T>)}?

— Carlos Scheidegger (@scheidegger) June 2, 2014

@scheidegger Thanks, Carlos! Not quite yet, but only because of a bug. I'm currently tracking it, and I'll look into addressing it soon

— Joe Pamer (@jopamer) June 2, 2014
0

Looks like Beta 3 still doesn't support recursive enums :-(

0

Beta 4 still doesn't support recursive enums!

0

Sorry to say, Beta 5 still doesn't support recursive enums!!

Unless

enum Tree { case Empty case Leaf(Int) case Node(Tree, Tree) }

isn't the right way to do it.

But the above continues to crash the REPL.

0

Swift 1.1 still doesn't support

enum Tree<T>{case Leaf(T); case Node(Tree<T>, Tree<T>)}

despite claims it was just a "bug" preventing it.