From 0ad682f2c139a76692abab7f0b9bf1dcd6433008 Mon Sep 17 00:00:00 2001 From: Mark Harrah Date: Sat, 7 May 2011 22:02:06 -0400 Subject: [PATCH] basic optional input support --- main/Structure.scala | 6 +++++- util/collection/Settings.scala | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/main/Structure.scala b/main/Structure.scala index 9ba0a1ef3..10e5e419f 100644 --- a/main/Structure.scala +++ b/main/Structure.scala @@ -145,7 +145,9 @@ object Scoped final def <<= (app: Initialize[S]): Setting[S] = setting(scoped, app) final def apply[T](f: S => T): Initialize[T] = Apply.single(scoped)(f) - def identity: Initialize[S] = apply(idFun) + final def identity: Initialize[S] = apply(idFun) + final def ? : Initialize[Option[S]] = Project.optional(scoped)(idFun) + final def ??[T >: S](or: => T): Initialize[T] = Project.optional(scoped)(_ getOrElse or ) final def get(settings: Settings[Scope]): Option[S] = settings.get(scope, key) } @@ -182,6 +184,8 @@ object Scoped def andFinally(fin: => Unit): App[S] = mk(_ andFinally fin) def doFinally(t: Task[Unit]): App[S] = mk(_ doFinally t) def identity: App[S] = mk(idFun) + def ? : Initialize[Task[Option[S]]] = Project.optional(scoped) { case None => mktask { None }; case Some(t) => t map some.fn } + def ??[T >: S](or: => T): Initialize[Task[T]] = Project.optional(scoped)( _ getOrElse mktask(or) ) def || [T >: S](alt: Task[T]): App[T] = mk(_ || alt) def && [T](alt: Task[T]): App[T] = mk(_ && alt) diff --git a/util/collection/Settings.scala b/util/collection/Settings.scala index 40d54de0d..60694120b 100644 --- a/util/collection/Settings.scala +++ b/util/collection/Settings.scala @@ -53,6 +53,7 @@ trait Init[Scope] def setting[T](key: ScopedKey[T], init: Initialize[T]): Setting[T] = new Setting[T](key, init) def value[T](value: => T): Initialize[T] = new Value(value _) + def optional[T,U](key: ScopedKey[T])(f: Option[T] => U): Initialize[U] = new Optional(Some(key), f) def update[T](key: ScopedKey[T])(f: T => T): Setting[T] = new Setting[T](key, app(key :^: KNil)(hl => f(hl.head))) def app[HL <: HList, T](inputs: KList[ScopedKey, HL])(f: HL => T): Initialize[T] = new Apply(f, inputs) def uniform[S,T](inputs: Seq[ScopedKey[S]])(f: Seq[S] => T): Initialize[T] = new Uniform(f, inputs) @@ -192,6 +193,14 @@ trait Init[Scope] override def toString = "setting(" + key + ")" } + private[this] final class Optional[S,T](a: Option[ScopedKey[S]], f: Option[S] => T) extends Initialize[T] + { + def dependsOn = a.toList + def map[Z](g: T => Z): Initialize[Z] = new Optional[S,Z](a, g compose f) + def get(map: Settings[Scope]): T = f(a map asFunction(map)) + def mapReferenced(g: MapScoped) = new Optional(mapKey(g), f) + private[this] def mapKey(g: MapScoped) = try { a map g.fn } catch { case _: Uninitialized => None } + } private[this] final class Joined[S,T,U](a: Initialize[S], b: Initialize[T], f: (S,T) => U) extends Initialize[U] { def dependsOn = a.dependsOn ++ b.dependsOn