zatonovo / lambda.r

Functional programming in R
216 stars 14 forks source link

Implement Haskell style typeclass? #23

Open kindlychung opened 9 years ago

kindlychung commented 9 years ago

How does lambda.r handle inheritance at the moment? I think a haskell style typeclass implementation would be awesome.

muxspace commented 9 years ago

You can create type hierarchies by calling another type constructor. Here's an example.

Matrix(x) %as% x
SquareMatrix(x) %when% { nrow(x) == ncol(x) } %as% { Matrix(x) }

dims(x) %::% Matrix : numeric
dims(x) %as% dim(x)

invert(x) %::% SquareMatrix : SquareMatrix
invert(x) %as% SquareMatrix(solve(x))

> x <- SquareMatrix(matrix(c(1,0,0,1),nrow=2))
> dims(x)
[1] 2 2
> invert(x)
     [,1] [,2]
[1,]    1    0
[2,]    0    1
attr(,"class")
[1] "SquareMatrix" "Matrix"       "matrix"