我通过visual studio创建了一个F#项目,增加了这样的功能:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
为什么这样的错误,在我的函数定义中?
它不是你的函数定义 - 它是你使用的方式printfn(F#编译器确实检查你是否使用给定格式字符串的正确参数).
所以通过做
printfn "%i,%i,%i" (fangle 3 4 5)
Run Code Online (Sandbox Code Playgroud)
你告诉F#到打印三个整数(分隔"") -你可以把它的类型是的printf "%i,%i,%i" : int -> int -> int -> unit-但你给它一个元组int*int*int(评估即结果fangle的a=3, b=4, c=5),所以现在F#是试图找出如何搭配int从printf "%i,%i,%i"类型的第一个curried类型int*int*int,我只是不能 - 因此错误.
明显的解决方法是:
printfn "%A" (fangle 3 4 5)
Run Code Online (Sandbox Code Playgroud)
在哪里告诉F#格式化生成的元组:
> printfn "%A" (fangle 3 4 5);;
(4, 5, 6)
val it : unit = ()
Run Code Online (Sandbox Code Playgroud)
或者你可以先解构元组:
> let (x,y,z) = fangle 3 4 5 in printfn "%i,%i,%i" x y z;;
4,5,6
val it : unit = ()
Run Code Online (Sandbox Code Playgroud)
或者你可以去弹道/幻想;)
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 = ()
Run Code Online (Sandbox Code Playgroud)
除了Carsten在他的回答中已经说过的内容之外,您还可以使用管道运算符|||>来解构元组,同时将它们作为参数传递给另一个函数:
let fangle a b c =
a+1, b+1, c+1
[<EntryPoint>]
let main argv =
fangle 3 4 5
|||> printfn "%i,%i,%i"
Run Code Online (Sandbox Code Playgroud)