最好的代碼是不存在的代碼,在這方面,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擴展會很難嗎?
uj5u.com熱心網友回復:
opam 中提供了一些 ppx 派生器,請嘗試opam search ppx. 例如,您可以使用ppx_deriving,例如,在 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/404600.html
標籤:
下一篇:如何將字串轉換為字串列?
