Ho molti programmi scritti in OCaml, alcuni usano i funtori. Ora, sto considerando di scrivere e riscrivere una parte di codice in F # (per beneficiare di alcuni vantaggi che OCaml non ha). Una cosa di cui ho paura è scrivere codice in F # per ciò che fanno i functors in OCaml.Come scrivere il codice in F # per ciò che fanno i funtori in OCaml?
Ad esempio, come è possibile emulare this example from OCaml manual in F #?
type comparison = Less | Equal | Greater
module type ORDERED_TYPE = sig
type t
val compare: t -> t -> comparison
end
module Set =
functor (Elt: ORDERED_TYPE) -> struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
[] -> [x]
| hd::tl ->
match Elt.compare x hd with
Equal -> s (* x is already in s *)
| Less -> x :: s (* x is smaller than all elements of s *)
| Greater -> hd :: add x tl
end
module OrderedString = struct
type t = string
let compare x y = if x = y then Equal else if x < y then Less else Greater
end
module OrderedInt = struct
type t = int
let compare x y = if x = y then Equal else if x < y then Less else Greater
end
module StringSet = Set(OrderedString)
module IntSet = Set(OrderedInt)
let try1() = StringSet.add "foo" StringSet.empty
let try2() = IntSet.add 2 IntSet.empty
Grazie per questa risposta dettagliata ... Quando si dice "approccio con mano pesante", vuoi dire che le persone nella pratica non codificano in questo modo? – SoftTimur
@SoftTimur: Sort of - Ho provato a non divergere molto dal codice originale, e non mi è sembrato naturale quando ho passato il tipo 'Set'. Non è lontano, ma avrei potuto trovare qualcosa di diverso se partissi da un foglio pulito. – scrwtp
@SoftTimur: forse sono solo i parametri di tipo contorto su 'Set'. – scrwtp