F# Type declaration possible ala Haskell?
I've looked a number of sources: it seems not possible to declare a type definition in F# ala Haskell:
' haskell type def:
myFunc :: int -> int
I'd like to use this type-def style in F#--FSI 开发者_运维技巧is happy to echo back to me:
fsi> let myType x = x +1;;
val myType : int -> int
I'd like to be explicit about the type def signature in F# as in Haskell. Is there a way to do this? I'd like to write in F#:
//invalid F#
myFunc : int -> int
myFunc x = x*2
The usual way is to do let myFunc (x:int):int = x+1
.
If you want to be closer to the haskell style, you can also do let myFunc : int -> int = fun x -> x+1
.
If you want to keep readable type declarations separately from the implementation, you can use 'fsi' files (F# Signature File). The 'fsi' contains just the types and usually also comments - you can see some good examples in the source of F# libraries. You would create two files like this:
// Test.fsi
val myFunc : int -> int
// Test.fs
let myFunx x = x + 1
This works for compiled projects, but you cannot use this approach easily with F# Interactive.
You can do this in F# like so to specify the return value of myType.
let myType x : int = x + 1
You can specify the type of the parameter, too.
let myType (x : int) : int = x + 1
Hope this helps!
See also The Basic Syntax of F# - Types (which discusses this aspect a little under 'type annotations').
Another option is to use "type abbreviations" (http://msdn.microsoft.com/en-us/library/dd233246.aspx)
type myType = int -> int
let (myFunc : myType) = (fun x -> x*2)
yes you can, by using lambda functions
myFunc : int -> int =
fun x -> x*2
this also avoids the problem in haskell of writing the function name twice.
精彩评论