简体   繁体   English

F#Type声明可能ala Haskell?

[英]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: 我看了很多来源:似乎不可能在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: 我想在F#中使用这种类型的def风格 - FSI很乐意回复我:

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. 我想在Haskell中明确说明F#中的类型def签名。 Is there a way to do this? 有没有办法做到这一点? I'd like to write in F#: 我想用F#写:

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

The usual way is to do let myFunc (x:int):int = x+1 . 通常的方法是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 . 如果你想更接近haskell风格,你也可以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). 如果要将可读类型声明与实现分开,可以使用“fsi”文件(F#签名文件)。 The 'fsi' contains just the types and usually also comments - you can see some good examples in the source of F# libraries. 'fsi'只包含类型,通常还包含注释 - 您可以在F#库的源代码中看到一些很好的示例。 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. 这适用于已编译的项目,但您无法使用F#Interactive轻松使用此方法。

Another option is to use "type abbreviations" ( http://msdn.microsoft.com/en-us/library/dd233246.aspx ) 另一种选择是使用“类型缩写”( http://msdn.microsoft.com/en-us/library/dd233246.aspx

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

You can do this in F# like so to specify the return value of myType. 您可以在F#中执行此操作,以指定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! 希望这可以帮助!

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

yes you can, by using lambda functions 是的,你可以使用lambda函数

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

this also avoids the problem in haskell of writing the function name twice. 这也避免了haskell写两次函数名的问题。

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

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