dup
, only works on boxed elements- To be able to duplicate
x
ingetCategory
, we need aboxed number
as a parameter - We are passing a boxed number to
getCategory
, unboxing it withdup
and we should box it again before return (read more about Stratification Condition). As we should box any return, the best place to put the#
if beforeif
.
def isTeenager: {x}
|x < 18|
def isAdult: {x}
|x < 60|
def getCategory: {x}
dup age = x
#if (isTeenager age)
then: "boring teenager"
else:
if (isAdult age)
then: "cool adult"
else: "respect the elder"
def main:
(getCategory #15)
Easy, right? Now assume that a teenager is someone with age less than or equal to 17. You have to work only with unboxed values to do it, that is, you can't use dup
. How you are going to fix it?
You have 3 options:
- Add 1 more parameter in
isTeenager
def isTeenager: {x} {y}
||x < 17| | |y == 17||
...
#if (isTeenager age age)
...
- Using a
pair
def isTeenager: {x}
get [aux1, aux2] = x
||aux1 < 17| | |aux2 == 17||
...
#if (isTeenager [age, age])
...
- Use
cpy
which can be used to copy numbers. Given a numbern
, returns&(n, n)
, apair
with two copies of the element.
def isTeenager: {x}
get [aux1, aux2] = cpy x
||aux1 < 17} | |aux2 == 17||
...
#if (isTeenager age)
...