speckledcarp
speckledcarp

Reputation: 6375

Why does this F# function need the extra sprintf to compile?

I'm an F# noob. I'm trying to create a function to format a results tuple, where the last element may or may not exist - since it's intended to hold any exceptions that might been caught during processing.

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"

See in the last line how I had to pipe the results of the first sprintf into the second sprintf? Basically, it tells me I've got a syntax error somewhere, and that the program isn't doing what I think it is. (Preliminary testing seems to be giving reasonable output, but it makes me nervous.)

Why does that compile, but this doesn't? It gives me the compile error "This expression was expected to have type string but here has type 'a * 'b * 'c * 'd".

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

Upvotes: 0

Views: 137

Answers (1)

sepp2k
sepp2k

Reputation: 370112

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

You're creating a tuple that contains the function returned by sprintf "..." name1 as its first element. The other elements of the tuple are name2, diff and ex. By passing that tuple to sprintf "%A", you're turning it into a string, making the types work. But of course that still won't make it do what you want.

To do what you want, get rid of the commas.

Upvotes: 2

Related Questions