Kevin Won
Kevin Won

Reputation: 7186

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

Upvotes: 30

Views: 4370

Answers (6)

Jannick Johnsen
Jannick Johnsen

Reputation: 19

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.

Upvotes: 0

LuddyPants
LuddyPants

Reputation: 441

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)

Upvotes: 1

Brian
Brian

Reputation: 118865

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

Upvotes: 1

Tomas Petricek
Tomas Petricek

Reputation: 243051

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.

Upvotes: 22

sepp2k
sepp2k

Reputation: 370162

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.

Upvotes: 29

sholsapp
sholsapp

Reputation: 16070

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!

Upvotes: 2

Related Questions