Ocaml:匹配一对中的一个项目

Eri*_*ric 4 ocaml functional-programming extract

我有一个接收temp的函数,这是一对.

type temp = (pd * string);;
Run Code Online (Sandbox Code Playgroud)

我想在temp中提取该字符串.但我不能编写一个可以匹配temp的函数,因为它是一个类型.

我写了一个函数:

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

但这给了我一个错误,说它不是一个功能.我基本上想要提取该字符串并将其打印出来.对此的任何意见将不胜感激.

ste*_*vez 7

你的解决方案几乎是正确的 - 你不需要"有趣的z - >"部分,看起来你可能有一个无关紧要的".相反,你需要模式匹配t,如下所示:

let print_temp (t:temp) (out:out_channel) : unit =
  match t with
    (_,a) -> output_string out a
Run Code Online (Sandbox Code Playgroud)

您还可以通过函数定义中的模式匹配更简洁地执行此操作:

let print_temp ((_,a):temp) (out:out_channel) : unit = output_string out a
Run Code Online (Sandbox Code Playgroud)

在你的代码中,你得到的类型错误告诉你,你声明print_temp返回单位,但实际上返回了一个函数(fun z - > ...).请注意,由于t:temp是您想要"拆开"的,因此您可以在其上进行模式匹配.