Defining sharp primitives (#> and <#) using Joy
icpdesign — 2005-09-23 12:45:16
#
# since Joy does not have the sharp integers data type, we use
# strings in the format "#nnnn" to represent a sharp integer
#
DEFINE
issharp == [string]
[uncons swap ['# =] [swap cons true] [swap cons false]
ifte]
[false]
ifte;
dig == [] swap 1 - [cons] times # pop nth element and push on top
dip;
peek == [] swap 1 - [cons] times # read nth element and push
swap dup [swap] dip swap dip; # on top
sdig == [issharp] [uncons swap pop 0 strtol dig] [] ifte;
speek == [issharp] [uncons swap pop 0 strtol peek] [] ifte;
END.
where the previously defined #> is named to sdig, and <# is named
speek.
First example:
10 20 30 [1 "#2" "#3" ["#2"] 2] [sdig] map
==> 10 20 30 [1 20 10 ["#2"] 2]
Second example: lets compute a*a + b*b + c*c :
3 4 5 ["#3" "#3" * "#2" "#2" * "#1" "#1" * + +] [speek] map i
==> 3 4 5 50
note that the elements 2 and 3 were not popped from the stack
because the map operator restore the old stack below the result,
but fortunately equal sharp integers are replaced by the same
stack element. Note that speek and sdig used with map returns
the same result!
Other examples:
dup == "#1" speek
swap == "#2" sdig
rollup == "#3" sdig "#3" sdig // X Y Z -> Z X Y
rolldown == "#3" sdig // X Y Z -> Y Z X
rotate == "#2" sdig "#3" sdig // X Y Z -> Z Y X
popd == "#2" sdig pop // Y Z -> Z
dupd == "#2" speek swap // Y Z -> Y Y Z
== "#2" speek "#2" sdig pop
swapd == "#2" sdig "#3" sdig "#3" sdig // X Y Z -> Y X Z
It would be interesting to add destructive and non destructive
versions of sbury, where the non-destructive version leaves the
buried element on top of the stack.
Why a sharp integer data type is needed?
look at the first and second examples, if we did not have the
sharp integers we will not be able to know where to apply sdig or
speek,
since they are selective in the sense they do something only if the
top
element of the stack is a sharp number; this needed if we want to use
sdig and speek with map operator as in the shown examples.
In summary, we saw that the sharp primitives can be defined using
Joy, and we just need to add sharp integer data type to Joy.
Taoufik Dachraoui