누군가 나를 펑터라고 설명 할 수 있습니까? 나는 간단한 예제를 원한다. 펑터를 사용해야 할 때?OCaml - 펑터 - 사용법?
4
A
답변
3
펑은 본질적으로 다른 모듈의 측면에서 모듈을 작성하는 방법입니다.
예쁜 전형적인 예는 표준 라이브러리에서 Map.Make
펑터이다. 이 펑터를 사용하여 특정 키 유형으로지도를 정의 할 수 있습니다. ocaml
이 생성 된 모듈의 특성을 도시
module Color = struct
type t = Red | Yellow | Blue | Green | White | Black
let compare a b =
let int_of_color = function
| Red -> 0
| Yellow -> 1
| Blue -> 2
| Green -> 3
| White -> 4
| Black -> 5 in
compare (int_of_color a) (int_of_color b)
end
module ColorMap = Map.Make(Color)
로드 :
여기 사소한 오히려 벙어리 예가
module Color :
sig
type t = Red | Yellow | Blue | Green | White | Black
val compare : t -> t -> int
end
module ColorMap :
sig
type key = Color.t
type 'a t = 'a Map.Make(Color).t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key -> 'a -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : (key -> 'a -> unit) -> 'a t -> unit
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val for_all : (key -> 'a -> bool) -> 'a t -> bool
val exists : (key -> 'a -> bool) -> 'a t -> bool
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> key * 'a
val max_binding : 'a t -> key * 'a
val choose : 'a t -> key * 'a
val split : key -> 'a t -> 'a t * 'a option * 'a t
val find : key -> 'a t -> 'a
val map : ('a -> 'b) -> 'a t -> 'b t
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
end
지도 어디에 구현하는 모듈을 만든 단순한 module ColorMap = Map.Make(Color)
키는 색상입니다. 그것은 ColorMap.singleton Color.Red 1
를 호출하고 통과 모듈 (Color
)가 Map.Make
펑의 요구 사항을 만족하기 때문에 Map.Make
의 사용이 일한 수에 1
참고 빨간색의지도를 취득하는 것이 가능합니다. 문서는 functor의 타입이 module Make: functor (Ord : OrderedType) -> S with type key = Ord.t
이라고 말합니다. : OrderedType
는 입력 모듈 (Color
)가 OrderedType
모듈 서명 (내가 더 공식적인 용어가있을거야) 일치한다는 것을 의미한다.
OrderedType
과 일치하도록 입력 모듈의 유형은 t
이고 compare
의 이름은 t -> t -> int
이어야합니다. 즉, t
유형의 값을 비교하는 방법이 있어야합니다. 보고있는 유형이 ocaml
인 경우 정확히 Color
입니다.
펑터를 사용하는
는 종종 몇 가지 디자인을 자신의 트레이드 오프 각이 있습니다 훨씬 더 어려운 질문이다. 하지만 대부분의 경우 라이브러리가 권장 방법으로 라이브러리를 제공 할 때 펑터를 사용할 것입니다.
이 [ocaml.org에 튜토리얼] (http://ocaml.org/learn/tutorials/modules.html)와 [현실 세계를 OCaml의 제 9 장 (https://realworldocaml.org/v1를 볼 수 있습니다 /en/html/functors.html). –
간단히 말하면, 펑터는 자바에서'인터페이스 '와 같습니다. –
@ JacksonTale, er, no. Java 인터페이스에 가장 가까운 것은 모듈 유형이며, 심지어 모듈 유형도 사실상 다릅니다. functor와 가장 가까운 것은 일반적인 클래스입니다. –