Reputation: 651
This works in F# Interactive:
let (list:(int * int) List) = []
list @ [(40, 60)];;
This doesent work in my program:
let rMouseEvent =
form.MouseClick.Add(fun args -> list @ [(args.X, args.Y)]))
Can someone explain why, and help me solve this?
The error says:
This expression was expected to have type
unit
but here has type
'a list -> 'a list
Upvotes: 1
Views: 86
Reputation: 144136
Your handler should not return a value, at present it returns an int * int list
. You could ignore it using ignore:
let rMouseEvent = form.MouseClick.Add(fun args -> list @ [(args.X, args.Y)] |> ignore)
although this is not very useful. If you want to add an item to list
, you could change it to a ResizeArray
:
let r = new ResizeArray<int * int>()
let rMouseEvent = form.MouseClick.Add(fun args -> r.Add((args.X, args.Y)))
alternatively you can use a ref:
let (r: (int*int) list ref) = ref []
let rMouseEvent = form.MouseClick.Add(fun args -> r := !r @ [(args.X, args.Y)])
Upvotes: 2
Reputation: 29100
The compile error you get indicates that the event handler was expected to return unit
- i.e. no value at all - but you're trying to return a (int * int) list
. The expected return type indicates that the caller isn't going to look after the value you return for you, so you need to store any values you change yourself.
If you want to stick with using lists, then make your original list into ref
:
let list : (int * int) List ref = ref []
and then do something like:
let rMouseEvent =
form.MouseClick.Add(fun args -> list := !list @ [(args.X, args.Y)]))
Upvotes: 2