2

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?

1 Answer 1

8

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 ()

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the additional information also, I'm relatively new to F# and come from an OO background. Little things like this can be a real grind!
Glad to see you appreciate the info. I think though for your example it might be better to use an interface rather than the record type.
Hey thanks again. I've been using a set of interfaces for the service layer in C# (an 'in' IInput and 'out' IOutput composed into an invariant IIOInterface) and they've been working great and interchangeably. However, with discriminated unions around I've created seperate service records with different type signatures (e.g. Load : string->('a * FileStream)) which may allow consumers to more adequately handle slight different requirements. However, I'll likely subclass these from a generic interface incase it becomes too heavyweight. I find juggling these new powers a big responsibility though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.