2013-05-14 37 views
10

是否有寫不使用符號中綴函數的方法嗎?類似這樣的:如何寫綴函數

let mod x y = x % y 
x mod y 

也許在「mod」之前的關鍵字什麼的。

+0

你可能感興趣的[This UserVoice issue](http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2313479-provide-the-option-of-having-infix-notation-在樂趣)。 – Daniel 2013-05-14 17:02:03

+0

您可能感興趣http://stackoverflow.com/questions/2210854/can-you-define-your-own-operators-in-f – ony 2013-05-14 17:05:57

回答

16

現有的答案是正確的 - 你不能在F#中定義一箇中綴函數(只是一個自定義的中綴運算符)。除了與運營商管道的把戲,你也可以使用擴展成員:

// Define an extension member 'modulo' that 
// can be called on any Int32 value 
type System.Int32 with 
    member x.modulo n = x % n 

// To use it, you can write something like this: 
10 .modulo 3 

注意.之前的空間是必要的,因爲否則編譯器試圖解釋10.m作爲數字文字(如10.0f)。

我覺得這有點比使用管道招更優雅,因爲F#支持實用的風格和麪向對象的風格和擴展方法是 - 在某種意義上 - 接近等同於隱含的運營商從實用的風格。流水線技巧看起來像是對操作符的輕微誤用(它最初可能看起來很混亂 - 或許比方法調用更令人困惑)。

這麼說,我看到人們使用其他運營商,而不是管道 - 也許是最有趣的版本是這樣的一個(也使用的事實,你可以省略的運營商空格):

// Define custom operators to make the syntax prettier 
let (</) a b = a |> b 
let (/>) a b = a <| b  
let modulo a b = a % b 

// Then you can turn any function into infix using: 
10 </modulo/> 3 

但即使這在F#世界中並不是一個成熟的習慣用法,所以我可能仍然更喜歡擴展成員。

+1

它已經有一段時間我寫/編碼任何東西,但是這看起來像它實現了同樣的事情,在C#擴展方法。甜! – Iter 2013-05-14 17:17:01

+2

@Iter這** **是一個擴展方法:) – 2013-05-14 17:33:09

+2

對不起,評論這個老帖子,但你的運營商對是錯:因爲運算符優先級,'10 3'等同於'模3 10',不'modulo 10 3'。一種解決方法是定義'let(/>)f x y = f y x'。或者,您可以使用另一對具有正確優先級的運算符,如'<.' and '.>'。 – Tarmil 2014-11-19 14:13:29

6

不,我知道的,但你可以使用左,右管道運營商。例如

let modulo x y = x % y 

let FourMod3 = 4 |> modulo <| 3 
+0

上面被認爲是'僞中綴' 沒有錯,它只是指向說出來,其實我喜歡這個符號有時候 – BoomTownTech 2015-10-14 20:36:26