Created
June 29, 2012 19:10
-
-
Save bkyrlach/3020023 to your computer and use it in GitHub Desktop.
More fun with DSL's...
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
package com.kyrlach.symbol | |
object Identifier { | |
val idents = new java.util.HashMap[Symbol, Identifier] | |
def set[T](s: Symbol, v: T) = { | |
println("Setting " + s + " to " + v) | |
idents.put(s, new Identifier{ type I = T; val init = v }) | |
} | |
def get[T](s: Symbol): T = { | |
println("Getting " + s) | |
idents.get(s) match { | |
case i: Identifier{type I = T} => i.init | |
case _ => throw new RuntimeException("Identifier not found.") | |
} | |
} | |
} | |
abstract class Identifier { | |
type I; | |
val init: I; | |
} | |
trait HavingSyntax { | |
def having[T](expr: => T):Unit = { | |
this match { | |
case g: Given => Identifier.set(g.s, expr) | |
} | |
} | |
} | |
object Given { | |
def a(s: Symbol): Given with HavingSyntax = new Given(s) with HavingSyntax | |
} | |
class Given(val s: Symbol) | |
class Stack[T](data: List[T]) { | |
def push(t: T): Stack[T] = new Stack(t :: data) | |
def pop(): (Option[T], Stack[T]) = (data.headOption, new Stack(data.tail)) | |
def size(): Int = data.size | |
} | |
object SymbolFun extends App { | |
implicit def s2v[T](s: Symbol):T = Identifier.get(s) | |
def stack_with[T](initial_contents: List[T]): Stack[T] = new Stack(initial_contents) | |
def pop[T](s: Stack[T]): Option[T] = s.pop._1 | |
Given a 'initial_contents having List(1,2,3) | |
Given a 'stack having stack_with('initial_contents) | |
println(pop('stack)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment