返回元组的函数的F#项目编译错误

Imm*_*ant 2 f# tuples return

我通过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)

在(fangle 3 4 5)的调用中有编译错误,它说:

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)

为什么这样的错误,在我的函数定义中?

Car*_*ten 7

它不是你的函数定义 - 它是你使用的方式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(评估即结果fanglea=3, b=4, c=5),所以现在F#是试图找出如何搭配intprintf "%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)


Jus*_*Guy 7

除了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)