Skip to content

Instantly share code, notes, and snippets.

@flyx
Created April 4, 2017 08:56
Show Gist options
  • Save flyx/2339540977a80a530ca716f615d230f8 to your computer and use it in GitHub Desktop.
Save flyx/2339540977a80a530ca716f615d230f8 to your computer and use it in GitHub Desktop.
type # concepts
Value[T] = concept v
v.value is T
MinValue[T] = concept v
v.minValue is T
MaxValue[T] = concept v
v.maxValue is T
RangedValue[T] = concept v
v is MinValue[T]
v is MaxValue[T]
type # implementations
BoolValue = ref object
value*: bool
FloatValue = ref object
minValue*, maxValue*: float
value*: float
IntValue = ref object
minValue*, maxValue*: int
value*: int
StringValue = ref object
value*: string
NoteValue = ref object
minValue*: 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:
echo "generated a min value impl"
if v < self.minValue: return false
when self is MaxValue:
echo "generated a max value impl"
if v > self.maxValue: 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(minValue:0, value:16)
f = FloatValue(minValue:0.0, maxValue: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