OCaml中的派生实现



最好的代码是不存在的代码,在这方面,Haskell对派生实现有很大的支持(deriving via使其变得更好(。

{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE KindSignatures, PolyKinds#-}
import Data.Kind (Type)
data NTree (a :: Type) =
NLeaf a
| NNode (NTree (a,a))
deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable)

据我所知,OCaml中也需要一些手动管道


type 'a n_tree = NLeaf of 'a | NNode of ('a * 'a) n_tree (* [@@deriving map] fails *)

let rec map_ntree : 'a 'b. 'a n_tree -> ('a -> 'b) -> 'b n_tree =
fun t f ->
match t with
| NLeaf x -> NLeaf (f x)
| NNode p -> NNode (map_ntree p (fun (l, r) -> (f l, f r)))

这些派生在OCaml中的状态是什么?

到目前为止,有没有更好的方法自动提供相应的证明树?

是否很难做出类似的更强大的deriving扩展?

在opam中有一些ppx Deriver可用,请尝试opam search ppx。例如,您可以使用ppx_derivation,例如,在OCaml顶级中

# #use "topfind";;
# #require "ppx_deriving.std";;
# type 'a n_tree = NLeaf of 'a | NNode of 'a * 'a n_tree 
[@@deriving show, eq, ord, iter, fold, map];;
type 'a n_tree = NLeaf of 'a | NNode of 'a * 'a n_tree
val pp_n_tree :
(Ppx_deriving_runtime.Format.formatter -> 'a -> Ppx_deriving_runtime.unit) ->
Ppx_deriving_runtime.Format.formatter ->
'a n_tree -> Ppx_deriving_runtime.unit = <fun>
val show_n_tree :
(Ppx_deriving_runtime.Format.formatter -> 'a -> Ppx_deriving_runtime.unit) ->
'a n_tree -> Ppx_deriving_runtime.string = <fun>
val equal_n_tree :
('a -> 'a -> Ppx_deriving_runtime.bool) ->
'a n_tree -> 'a n_tree -> Ppx_deriving_runtime.bool = <fun>
val compare_n_tree :
('a -> 'a -> Ppx_deriving_runtime.int) ->
'a n_tree -> 'a n_tree -> Ppx_deriving_runtime.int = <fun>
val iter_n_tree : ('a -> unit) -> 'a n_tree -> unit = <fun>
val fold_n_tree : ('a -> 'b -> 'a) -> 'a -> 'b n_tree -> 'a = <fun>
val map_n_tree : ('a -> 'b) -> 'a n_tree -> 'b n_tree = <fun>

最新更新