functional programming - Scala class wrapping a partially applied constructor - how to use it to create API methods? -
i'm trying create simple api dealing intervals of hours. (i'm aware of joda time, , i'm not trying reinvent it. rather exercise).
what achieve this:
(1)
assert(from("20:30").to("20:50") == interval("20:30", "20:50") ) //same thing, without implicit defs assert(from(time(20, 30)).to(time(20, 50)) == interval(time(20, 30), time(20, 50)))
(2)
assert(from("20:30").forminutes(10) == from("20:30").to("20:40"))
have managed implement (1), this: (ignoring tostring, ordered trait, a.s.o)
case class time(hour: int, minute: int) case class interval(start: time, end: time) object interval { case class halfinterval(half: time => interval) { def to(time: time): interval = half(time) def forminutes(minutes: int): interval = ??? } def from(start: time): halfinterval = halfinterval(interval(start, _)) } object time { def apply(hourminute: string): time = { val tries = hourminute.split(":").map(s => try(s.toint)) tries match { case array(success(hour), success(minute)) => time(hour, minute) case _ => throw new illegalargumentexception } } implicit def stringtotime(hourminute: string) = time(hourminute) }
however, don't know how implement (2) (that is: interval.forminutes).
def forminutes(minutes: int): interval = { val time = ?? // based on time object construct new time object here? half(time) }
can't seem wrap head around this.
"halfinterval" wrapper on time => interval
make sense @ all?
designed empirically - from(..).to(..)
calls work planned - rather functional-conceptual model in mind.
there better way achieve api?
thanks
this do:
object interval { case class halfinterval(start: time) { def to(end: time): interval = interval(start, end) def forminutes(minutes: int): interval = to(getend(start, minutes)) private def getend(start: time, minutes: int) = ??? } def from(start: time): halfinterval = halfinterval(start) }
getend() adds minutes parameter start.minute, divided 60, adds result start.hours , rest of division minutes , there build end time. (then maybe hour modulus 24 in case go next day).
edit: halfinterval should value class, don't worry that.
Comments
Post a Comment