Created
November 15, 2011 16:09
-
-
Save mariogleichmann/1367451 to your computer and use it in GitHub Desktop.
Product type, only based on support for sum type, functions and pattern matching (Product Type as Function over sum Type) ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a very simple kind of union type - or you might say 'another Either' | |
object Sum{ | |
abstract trait OR[+A,+B] | |
case class FST[A,B]( a:A ) extends OR[A,B] | |
case class SND[A,B]( b:B ) extends OR[A,B] | |
} | |
// a simple Product type, based on sum types | |
object Product{ | |
import Sum._ | |
// Product, implemented as a Function | |
type x[A,B] = Int => A OR B | |
// constructor - unfortunately we must adhere to 'A x B' and therefore the function can't simply return A xor B | |
// (but something of type 'A OR B' ), which is kind of ugly | |
def pair[A,B]( a :A, b :B ) : A x B = i => if( i == 0 ) FST(a) else SND(b) | |
// selectors - if we don't want to use 'OO-style message passing by using dot-operator' we're forced to do pattern matching | |
// since our type function always returns something of type 'A OR B' (see constructor), which is again kind of ugly | |
def fst[A,B]( p :A x B ) :A = p(0) match{ case FST(a) => a } | |
def snd[A,B]( p :A x B ) :B = p(1) match{ case SND(b) => b } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment