Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# project compiling error for a function returning a tuple

Tags:

return

tuples

f#

I created an F# project by visual studio, added function like this:

let fangle a b c =
  a+1, b+1, c+1

[<EntryPoint>]
let main argv = 
printfn "%i,%i,%i" (fangle 3 4 5) // compile error

There's compiling error at the call of (fangle 3 4 5), it says:

Error 2 The type '(int * int * int)' is not compatible with any of the types
byte,int16,int32,int64,sbyte,uint16,uint32,uint64,nativeint,unativeint,
arising from the use of a printf-style format string 
C:\Users\mis\Documents\Visual Studio 2013\Projects\ConsoleApplication1\ConsoleApplication3\Program.fs 20 25 ConsoleApplication3

Why such an error, in my function definition?

like image 801
gongliming7 Avatar asked Aug 12 '26 04:08

gongliming7


1 Answers

it's not your function definition - it's the way you use printfn (the F# compiler is indeed checking if you use the right parameters for the given format-string).

So by doing

printfn "%i,%i,%i" (fangle 3 4 5)

you are telling F# to print three integers (separated by ',') - you can think of it's type to be printf "%i,%i,%i" : int -> int -> int -> unit - but you give it a tuple int*int*int (namely the result of evaluating fangle for a=3, b=4, c=5) so now F# is trying to figure out how to match the first curried type int from printf "%i,%i,%i" with the type int*int*int and I just cannot - therefore the error.

The obvious fix would be:

printfn "%A" (fangle 3 4 5)

where you tell F# to format the resulting tuple:

> printfn "%A" (fangle 3 4 5);;
(4, 5, 6)
val it : unit = ()

or you can first deconstruct the tuple:

> let (x,y,z) = fangle 3 4 5 in printfn "%i,%i,%i" x y z;;
4,5,6
val it : unit = ()

or you can go ballistic/fancy ;)

let uncurry3 f (x,y,z) = f x y z

> uncurry3 (printfn "%i,%i,%i") (fangle 3 4 5);;
4,5,6
val it : unit = ()
like image 141
Random Dev Avatar answered Aug 13 '26 18:08

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!