F# Type declaration possible ala Haskell?

那年仲夏 提交于 2019-12-09 07:38:23

问题


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

回答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.




回答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.




回答3:


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!




回答4:


See also The Basic Syntax of F# - Types (which discusses this aspect a little under 'type annotations').




回答5:


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)



回答6:


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.



来源:https://stackoverflow.com/questions/3713233/f-type-declaration-possible-ala-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!