しかし、継承のように実装があるclassを継承したいときがあります。
例えばこんなコードがあります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defprotocol Sequence | |
(add [xs x]) | |
(empty [xs]) | |
(head [xs]) | |
(tail [xs])) | |
(defrecord Cons [x xs] | |
Sequence | |
(add [xs x] (Cons. x xs)) | |
(empty [xs] (Nil.)) | |
(head [_] x) | |
(tail [_] xs)) | |
(defrecord Nil [] | |
Sequence | |
(add [xs x] (Cons. x xs)) | |
(empty [xs] (Nil.)) | |
(head [_] nil) | |
(tail [xs] xs)) | |
(defrecord Wrapped [list] | |
Sequence | |
(add [xs x] | |
(update-in xs [:list] (partial cons x))) | |
(empty [xs] | |
(Wrapped. '())) | |
(head [xs] | |
(first list)) | |
(tail [xs] | |
(update-in xs [:list] rest))) |
ConsとNilのaddとemptyの実装が同じです。
共通化したい。
とりあえず、addとemptyを別Protocolに。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defprotocol Sequence | |
(head [xs]) | |
(tail [xs])) | |
(defprotocol Adder | |
(add [xs x]) | |
(empty [xs])) |
ListというProtocolを作って、それに対するAdderを定義します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defprotocol List | |
(list [xs])) | |
(extend-type List | |
Adder | |
(add [xs x] (Cons. x xs)) | |
(empty [xs] (Nil.))) |
ConsとNilに対してListを実装すれば、めでたしめでたし。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defrecord Cons [x xs] | |
List | |
(list [xs] xs) | |
Sequence | |
(head [_] x) | |
(tail [_] xs)) | |
(defrecord Nil [] | |
List | |
(list [xs] xs) | |
Sequence | |
(head [_] nil) | |
(tail [xs] xs)) |
0 件のコメント:
コメントを投稿