2011-05-05 37 views
4

我有一個函數,它接受一個temp,這是一對。Ocaml:匹配一對中的一個項目

type temp = (pd * string);; 

我想在temp中提取該字符串。但是我不能寫一個函數,因爲它的類型只能匹配temp。

我寫了一個函數:

let print_temp(t:temp) (out: out_channel) : unit = 
    fun z -> match z with 
      (_,a) -> output_string out a " 
;; 

但是,這給了我一個錯誤說,它不是一個功能。我基本上想要提取該字符串並打印出來。任何對此的意見,將不勝感激。

回答

7

您的解決方案几乎是正確的 - 你並不需要的「樂趣ž - >」的一部分,它看起來像你可能有外來」相反,你需要模式匹配對T,像這樣:

let print_temp (t:temp) (out:out_channel) : unit = 
    match t with 
    (_,a) -> output_string out a 

你也可以做到這一點更簡潔的模式在功能定義相匹配:

let print_temp ((_,a):temp) (out:out_channel) : unit = output_string out a 

在代碼中,你得到的錯誤類型是告訴你,你聲明print_temp返回單位,但實際上返回一個函數(fun z - > ...)。請注意,由於t:temp是你的w螞蟻「分開」,它是有道理的,你會模式匹配。

0

而不是

match t with (_, a) -> output_string out a 

可以使用的功能FST(和SND

let a = fst t in output_string out a 

甚至更​​簡潔

output_string out (fst t)