Carp/core/Byte.carp
scottolsen 040e9e4391 Add an implements primitive, update core
This change adds a new primitive Implements which changes interface
implementations from being implicit to being explicit. Going forward,
users will have to declare (implements <interface> <implementation>) to
explicitly add a function to an interface. This provides two benefits:

- Prevents unwitting name clashes. Previously, if one defined a function
  that happened to have the same name as an interface, it was
  automatically assumed the function implemented that interface when this
  is not always the intention, especially in large programs.
- Name flexibility. One can now implement an interface with a function
  that has a different name than the interface, which allows for greater
  flexibility.

I've updated core to make the necessary calls to the new primitive.

Since str and copy are derived automatically for types, we treat these
functions as a special case and auto-implement the interfaces.
2020-05-09 12:59:47 -04:00

88 lines
2.0 KiB
Plaintext

(system-include "carp_byte.h")
(defmodule Byte
(register = (λ [Byte Byte] Bool))
(register copy (λ [&Byte] Byte))
(register + (λ [Byte Byte] Byte))
(register - (λ [Byte Byte] Byte))
(register * (λ [Byte Byte] Byte))
(register / (λ [Byte Byte] Byte))
(register < (λ [Byte Byte] Bool))
(register > (λ [Byte Byte] Bool))
(register mod (λ [Byte Byte] Byte))
(register inc (λ [Byte] Byte))
(register dec (λ [Byte] Byte))
(register to-int (λ [Byte] Int))
(register from-int (λ [Int] Byte))
(defn zero [] 0b)
(implements = Byte.=)
(implements copy Byte.copy)
(implements + Byte.+)
(implements - Byte.-)
(implements * Byte.*)
(implements / Byte./)
(implements < Byte.<)
(implements > Byte.>)
(implements mod Byte.mod)
(implements inc Byte.inc)
(implements dec Byte.dec)
(implements zero Byte.zero)
(implements to-int Byte.to-int)
(implements from-int Byte.from-int)
)
(defmodule Byte
(register bit-shift-left (λ [Byte Byte] Byte))
(register bit-shift-right (λ [Byte Byte] Byte))
(register bit-and (λ [Byte Byte] Byte))
(register bit-or (λ [Byte Byte] Byte))
(register bit-xor (λ [Byte Byte] Byte))
(register bit-not (λ [Byte] Byte))
(defn even? [a] (= (mod a 2b) 0b))
(defn odd? [a] (not (even? a)))
(defn add-ref [x y]
(Byte.+ @x @y))
;; Move to generic math module?
(defn clamp [min, max, val]
(if (> val max)
max
(if (< val min)
min
val)))
(doc pow "Raise x to the power of y.")
(defn pow [x y]
(let-do [r 1b]
(while (/= y 0b)
(do
(when (/= (bit-and y 1b) 0b)
(set! r (* r x)))
(set! y (/ y 2b))
(set! x (* x x))))
r))
(implements pow Byte.pow)
(implements add-ref Byte.add-ref)
)
(defmodule ByteRef
(defn = [a b]
(Byte.= @a @b))
(defn < [a b]
(Byte.< @a @b))
(defn > [a b]
(Byte.> @a @b))
(implements = ByteRef.=)
(implements < ByteRef.<)
(implements > ByteRef.>)
)