Created
February 20, 2019 12:09
-
-
Save dovideh/cc22f8d78df013ca5dc2a8809a8f2ea7 to your computer and use it in GitHub Desktop.
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
type # concepts | |
BasicValue[T] = concept v | |
v.value is T | |
MinValue[T] = concept v | |
v is BasicValue[T] | |
v.min is T | |
MaxValue[T] = concept v | |
v is BasicValue[T] | |
v.max is T | |
RangedValue[T] = concept v | |
v is MinValue[T] | |
v is MaxValue[T] | |
Value[T] = concept v | |
(v is RangedValue[T] or | |
v is MinValue[T] or | |
v is MaxValue[T] or | |
v is BasicValue[T]) | |
type # implementations | |
BoolValue = ref object | |
value*: bool | |
FloatValue = ref object | |
min*, max*: float | |
value*: float | |
IntValue = ref object | |
min*, max*: int | |
value*: int | |
StringValue = ref object | |
value*: string | |
NoteValue = ref object | |
min*: int | |
value*: int | |
# generic set will produce multiple implementations | |
proc set[T](self: Value, v: T): bool = | |
# following block only compiled when expr is true | |
when self is MinValue[T]: | |
echo "generated a min value impl" | |
if v < self.min: return false | |
when self is MaxValue[T]: | |
echo "generated a max value impl" | |
if v > self.max: return false | |
echo "generated a basic impl" | |
self.value = v | |
return true | |
# checking whether our types are valid for the concepts | |
when BoolValue is Value: | |
echo "BoolValue is Value" | |
when NoteValue is MinValue: | |
echo "NoteValue is MinValue" | |
when FloatValue is RangedValue: | |
echo "FloatValue is RangedValue" | |
# proving it works | |
let | |
b = BoolValue(value: false) | |
n = NoteValue(min:0, value:16) | |
f = FloatValue(min:0.0, max:1000.0, value: 0.0) | |
# set boolean | |
discard b.set(true) | |
# set note then set under min | |
discard n.set(8) | |
discard n.set(-1) | |
# set float then set over max | |
discard f.set(100.0) | |
discard f.set(10001.0) | |
echo "b is ", b.value, " vs true" | |
echo "n is ", n.value, " vs 8" | |
echo "f is ", f.value, " vs 100.0" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment