为什么这个F#函数需要额外的sprintf来编译?

时间:2014-04-27 01:34:04

标签: f#

我是F#noob。我试图创建一个函数来格式化结果元组,其中最后一个元素可能存在也可能不存在 - 因为它旨在保存在处理过程中可能捕获的任何异常。

let formatResults resultsTuple =
  match resultsTuple with
  |(name1, name2, diff, count, correlation, None) -> (sprintf "%A and %A with diff %A had %A pairs and showed a correlation coefficient of %A" name1 name2 diff count correlation)
  |(name1, name2, diff, _, _, Some(ex)) -> (sprintf "Error: %A and %A with diff %A threw exception %A" name1, name2, diff, ex) |> sprintf "%A"

在最后一行中看到我如何将第一个sprintf的结果输入第二个sprintf?基本上,它告诉我,我在某个地方遇到了语法错误,而且该程序并没有按照我的想法行事。 (初步测试似乎给出了合理的结果,但这让我很紧张。)

为什么要编译,但这不是吗?它给了我编译错误&#34;这个表达式应该有类型字符串,但这里有类型&#39; a *&#39; b *&#39; c *&#39; d&#34;。< / p>

let formatResults resultsTuple =
  match resultsTuple with
  |(name1, name2, diff, count, correlation, None) -> sprintf "%A and %A with diff %A had %A pairs and showed a correlation coefficient of %A" name1 name2 diff count correlation
  |(name1, name2, diff, _, _, Some(ex)) -> sprintf "Error: %A and %A with diff %A threw exception %A" name1, name2, diff, ex

1 个答案:

答案 0 :(得分:2)

sprintf "Error: %A and %A with diff %A threw exception %A" name1, name2, diff, ex

您正在创建一个包含sprintf "..." name1返回的函数作为其第一个元素的元组。元组的其他元素是name2diffex。通过将该元组传递给sprintf "%A",您将其转换为字符串,使类型工作。但当然,这仍然不能使它做你想做的事。

要做你想做的事,摆脱逗号。