I have a function that takes in a temp, which is a pair.
type temp = (pd * string);;
I want to extract that string in temp. But I can't write a function that can just matc开发者_高级运维h on temp since its a type.
I wrote a function:
let print_temp(t:temp) (out: out_channel) : unit =
fun z -> match z with
(_,a) -> output_string out a "
;;
But that gives me an error saying its not a function. I basically want to extract that string and print it. Any input on this would be appreciated.
Your solution is almost correct -- you don't need the "fun z ->" part, and it looks like you might have an extraneous ". Instead, you need to pattern match against t, like this:
let print_temp (t:temp) (out:out_channel) : unit =
match t with
(_,a) -> output_string out a
You can also do this more succinctly by pattern matching in the function definition:
let print_temp ((_,a):temp) (out:out_channel) : unit = output_string out a
In your code, the type error you get is telling you that you declared print_temp to return unit, but actually returned a function (fun z -> ...). Note that since the t:temp is what you want to "take apart", it makes sense that you would pattern match on it.
Instead of
match t with (_, a) -> output_string out a
you can also use the functions fst (and snd)
let a = fst t in output_string out a
or even more concise
output_string out (fst t)
精彩评论