tags:

views:

389

answers:

4

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?

A: 

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!

gnucom
Citation: http://msdn.microsoft.com/en-us/library/dd233229.aspx
gnucom
+7  A: 

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.

sepp2k
I know you can specify types that way with your actual function definition--that's not exactly what I'm asking. thanks though.
Kevin Won
@Kevin: Make sure you understand the difference between a type annotation and a type definition.
Jon Harrop
+7  A: 

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.

Tomas Petricek
I find the Haskell Type def style (and the .fsi way) such as useful way to 'sketch' in F#. any idea why FSI doesn't support this--and why you can't just do these sigs in line? Is that more of the OCaml tradition?
Kevin Won
@Kevin: I'm not really sure, but I agree that the Haskell way looks more readable then mixed header/type annotations. It is probably the OCaml tradition, because I don't think there is any technical issue with this. Writing them inline would make sense... (Another question is whether this is worth the limited F# team resources at this point)
Tomas Petricek
thanks Tomas. Just for the record, F# team, pretty please? in-line time annotations?
Kevin Won
I would like them too, but sorry, the ship has sailed for syntax here, and we've no plans for an 'additive' change. See also http://stackoverflow.com/questions/979084/what-features-would-you-add-remove-or-change-in-f
Brian
Also note that the .fsi is checked after the .fs, so you might still need some type annotations in the .fs to make the type inferencer happy.
Nathan Sanders
@Tomas: This is possible. Don Syme actually asked me if I wanted this and I said "no". :-)
Jon Harrop
+1  A: 

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

Brian