mirror of
https://github.com/carp-lang/Carp.git
synced 2024-11-05 04:44:12 +03:00
b61a439e29
Constrained interfaces require little change to core carp. In rare cases (illustrated in test/interfaces.carp) we need to make our functions slightly more specific. This weakens inference slightly, but in my opinion is a reasonable case of weakness and not a fault of the type system. Exceptional cases that were typed `a-> a` that is, cases that relied on the previous typing errors related to interfaces, as might be expected, no longer work (as is the case for the higher-order use of fmap in examples/functor.carp). Aside from that, nothing changes.
51 lines
1.3 KiB
Plaintext
51 lines
1.3 KiB
Plaintext
;; Test Interfaces
|
|
|
|
(load "Test.carp")
|
|
(use Test)
|
|
|
|
(definterface foo (Fn [a] Int))
|
|
|
|
;; A module implements an interface using implements.
|
|
;; Implementations don't need to share names with interfaces.
|
|
(defmodule A
|
|
(defn bar [x] x)
|
|
(implements foo A.bar))
|
|
|
|
;; Implementations may be declared before definitions
|
|
;; like `doc`, the name is relative to the module environment
|
|
(defmodule B
|
|
(implements foo baz)
|
|
(defn baz [y] (if y 5 0)))
|
|
|
|
;; Interfaces may be implemented retroactively
|
|
;; global functions can also implement interfaces.
|
|
(sig gojira (Fn [&String] String))
|
|
(defn gojira [s] @s)
|
|
(implements monster gojira)
|
|
|
|
(definterface monster (Fn [a] String))
|
|
|
|
;; An interface name can be used as a default implementation
|
|
(defn monster [scary?] (if scary? @"RAWR" @"meow"))
|
|
(implements monster monster)
|
|
|
|
(deftest test
|
|
(assert-equal test
|
|
&2
|
|
&(foo 2) ;; A.foo
|
|
"Implements works as expected.")
|
|
(assert-equal test
|
|
&5
|
|
&(foo true) ;; B.foo
|
|
"Implementations can be declared before definitions.")
|
|
(assert-equal test
|
|
"SKRYEEE"
|
|
&(monster "SKRYEEE")
|
|
"Interfaces can be implemented retroactively.")
|
|
(assert-equal test
|
|
"meow"
|
|
&(monster false)
|
|
"Implementations may be global, and an implementation with the same name may
|
|
be used as a default.")
|
|
)
|