Adam Kewley
Adam Kewley

Reputation: 1234

Putting a ()->int into an F# type

I have an application that uses a (generic) service to perform IO actions. I want to aggregate the usual IO functions (Save, SaveAs, etc.) into an F# type but the compiler seems to dislike this notation:

type InputService<'a> = {
    // Fine
    SomeFunc : 'a -> Option<'a>

    // Error (VS2012): "Anonymous type variables are not permitted in this declaration"
    Save : 'a -> ()

    // Error (see above)
    Load : () -> 'a
}

I'm aware that stateful functions like this may not be idiomatic. In reality, I plan on currying in UI prompts, file paths, etc but is it possible to define that function signature in my type?

Upvotes: 2

Views: 188

Answers (1)

John Palmer
John Palmer

Reputation: 25516

It appears that in this notation you need to write

type InputService<'a> = {
    SomeFunc : 'a -> Option<'a>  
    Save : 'a -> unit
    Load : unit -> 'a
}

i.e. write unit instead of ()

You can see a simpler example here

let t : () = ();;

produces the same error message, but writing unit works fine.

The reason for these error messages is that () is a constant like 1. Obviously you can't write

let t : 1 = 1;;

So the same applies to ()

Upvotes: 8

Related Questions