Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created August 14, 2012 05:28
Show Gist options
  • Select an option

  • Save fearofcode/3346583 to your computer and use it in GitHub Desktop.

Select an option

Save fearofcode/3346583 to your computer and use it in GitHub Desktop.
a first try at representing expressions in trees for later use in a gentic programming library
package org.wkh.learningscala
case class GPFunction[T](f: List[T] => T, name: String) {
def apply(x: List[T]) = f(x)
override def toString = name
}
case class GPTerminal[T](f: Map[String, T] => T, name: String) {
def apply(env: Map[String, T]): T = f(env)
override def toString = name
}
object GPTerminal {
implicit def constantToTerminal[T](c: T): GPTerminal[T] = new GPTerminal[T]((_: Map[String, T]) => c, c.toString)
implicit def keyToTerminal[T](s: String): GPTerminal[T] = new GPTerminal[T]((env: Map[String, T]) => env(s), s)
}
abstract class GPNode[T] {
def apply(env: Map[String, T]): T
}
class GPFunctionNode[T](f: GPFunction[T], children: List[GPNode[T]]) extends GPNode[T] {
def apply(env: Map[String, T]): T = {
val childrenValues = children.map(c => c.apply(env))
f(childrenValues)
}
override def toString = "(" + f.name + " " + children.map(_.toString).mkString(" ") + ")"
}
class GPTerminalNode[T](f: GPTerminal[T]) extends GPNode[T] {
def apply(env: Map[String, T]): T = f(env)
override def toString = f.name
}
object LearningScala extends App {
val env = Map("x" -> 1, "y" -> 2)
val oneNode = new GPTerminalNode(1)
val twoNode = new GPTerminalNode(2)
val xValNode = new GPTerminalNode[Int]("x")
val yValNode = new GPTerminalNode[Int]("y")
val plusFunc = GPFunction((lst: List[Int]) => lst(0) + lst(1), "+")
val timesFunc = GPFunction((lst: List[Int]) => lst(0) * lst(1), "*")
val yTimesTwo = new GPFunctionNode(timesFunc, List(yValNode, twoNode))
val terminals = List(xValNode, oneNode)
val nodeArgs: List[GPNode[Int]] = List(yTimesTwo, oneNode)
// (y*2) + 1
val tree = new GPFunctionNode(plusFunc, nodeArgs)
println(tree + " == " + tree(env)) // (+ (* y 2) 1) == 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment