繁体   English   中英

F#Type声明可能ala Haskell?

[英]F# Type declaration possible ala Haskell?

我看了很多来源:似乎不可能在F#ala Haskell中声明一个类型定义:

' haskell type def:
myFunc :: int -> int

我想在F#中使用这种类型的def风格 - FSI很乐意回复我:

fsi> let myType x = x +1;;

val myType : int -> int

我想在Haskell中明确说明F#中的类型def签名。 有没有办法做到这一点? 我想用F#写:

//invalid F#
myFunc : int -> int
myFunc x = x*2

通常的方法是let myFunc (x:int):int = x+1

如果你想更接近haskell风格,你也可以let myFunc : int -> int = fun x -> x+1

如果要将可读类型声明与实现分开,可以使用“fsi”文件(F#签名文件)。 'fsi'只包含类型,通常还包含注释 - 您可以在F#库的源代码中看到一些很好的示例。 您将创建两个这样的文件:

// Test.fsi
val myFunc : int -> int

// Test.fs
let myFunx x = x + 1

这适用于已编译的项目,但您无法使用F#Interactive轻松使用此方法。

另一种选择是使用“类型缩写”( http://msdn.microsoft.com/en-us/library/dd233246.aspx

type myType = int -> int
let (myFunc : myType) = (fun x -> x*2)

您可以在F#中执行此操作,以指定myType的返回值。

let myType x : int = x + 1

您也可以指定参数的类型。

let myType (x : int) : int = x + 1

希望这可以帮助!

另请参阅F#的基本语法 - 类型 (在“类型注释”下稍微讨论了这个方面)。

是的,你可以使用lambda函数

myFunc : int -> int =
  fun x -> x*2

这也避免了haskell写两次函数名的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM