[英]declare a generic function in f#
I am trying to write my first generic function in F#, and it looks like I am missing some concept here : 我试图用F#编写我的第一个泛型函数,但似乎这里缺少一些概念:
module Assert =
let ThrowsException<'e : exn> functionUnderTest =
try
let result = functionUnderTest
printfn "fails"
with
| :? 'e -> printfn "succeeds"
| _ -> printfn "fails"
stdin(18,28): error FS0010: Unexpected symbol ':' in pattern. stdin(18,28):错误FS0010:模式中出现意外的符号“:”。 Expected '>' or other token.
预期为“>”或其他标记。
I would like to be able to use my function like that to test if an exception was raised. 我希望能够使用类似的功能来测试是否引发了异常。
let myFunction=HttpClient.postDocRaw "http://notexisting.com/post.php" "hello=data"
Assert.ThrowsException System.Net.WebException myFunction
I would like to achieve this tool for testing so if anybody has a solution , that's nice, but furthermore, I am learning F#, and I would like to know where I go wrong trying to write functions like this. 我想实现此工具进行测试,因此,如果有人有解决方案,那很好,但是此外,我正在学习F#,并且我想知道在尝试编写此类函数时出错了。
final code : 最终代码:
module Assert =
let ThrowsException<'e when 'e :> exn> functionUnderTest =
try
let actual = functionUnderTest()
printfn "succeeds"
with
| :? 'e -> printfn "succeeds"
| _ -> Assert.Fail()
[<TestClass>]
type HttpClientTest() =
[<TestMethod>]
member x.PostDataWrongUrl() =
Assert.ThrowsException<System.Net.WebException> (fun() -> HttpClient.postDocRaw "http://notexisting.com/post.php" "hello=data")
The error says "Expected '>'" because a type constraint takes the form 'T when 'T :> baseType
. 该错误显示“ Expected'>'”,因为类型约束
'T when 'T :> baseType
。 Your code should be: 您的代码应为:
module Assert =
let ThrowsException<'e when 'e :> exn> functionUnderTest =
try
let result = functionUnderTest
printfn "fails"
with
| :? 'e -> printfn "succeeds"
| _ -> printfn "fails"
See Constraints on MSDN for more info. 有关更多信息,请参见MSDN上的约束 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.