2017-02-21 69 views
1

我想代表一些標量值(例如整數或字符串) 或者它的實際值或某些NA值,並稍後將它們存儲在集合(例如列表)中 。目的是處理缺失的值。OCaml簽名與多種類型

要做到這一點,我實現了一個簽名

module type Scalar = sig 
    type t 
    type v = Value of t | NA 
end 

現在我心裏有一個包含Scalar小號一些多態性Vector類型。基本上,以下一些

module Make_vector(S: Scalar) = struct 
    type t = S.v list 

    ... rest of the functor ... 
end 

但是,我不能得到這個工作。我想做類似

module Int_vector = Make_vector(
    struct 
     type t = int 
    end 
) 

module Str_vector = Make_vector(
    struct 
     type t = string 
    end 
) 

... and so on for some types. 

我還沒有與OCaml工作過很多,所以也許這不是正確的方法。任何建議如何實現這種多態標量與和類型?

編譯器總是與以下消息響應:

The parameter cannot be eliminated in the result type. 
Please bind the argument to a module identifier. 

之前,我曾試圖實施Scalar作爲總和類型,但由於實現巨大match條款的某些功能時遇到了 複雜性問題。另一個(imo不太好)選項將使用option。這是一個更好的策略嗎?

回答

0

據我所見,你正在構造v作爲你的函子的輸入類型,但你真的希望它是一個輸出類型。然後,當您應用仿函數時,您只提供類型t,但不提供v。我的建議是將v的定義轉換爲Make_vector的實現。

+0

還沒想過!現在它可以工作。謝謝 :) – teekay

0

你想要完全使用模塊/函子嗎?爲什麼簡單'a option list不夠好?您可以在其上運行功能,例如

let rec count_missing ?acc:(acc=0) = function 
    | None::tail -> count_missing ~acc:(acc+1) tail 
    | _::tail -> count_missing ~acc tail 
    | [] -> acc ;; 


val count_missing : ?acc:int -> 'a option list -> int = <fun> 

count_missing [None; Some 1; None; Some 2] ;; 
- : int = 2 

count_missing [Some "foo"; None; Some "bar"] ;; 
- : int = 1