I want to test the headOrDefault in F# on an empty array, which is supposed to work like FirstOrDefault in C#. So I typed in this code:
let arr = []
let res = query {
for e in arr do
select e
headOrDefault
}
Console.WriteLine("{0}", (res = null))
I would expect res
to get the value null.
But this code doesn't even compile. I get this compile error:
Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic.
The compiler underlines arr
in this line as the problem:
for e in arr do
Why won't this compile, and how can I get it to work (using headOrDefault)?
Thanks!
[] is not an array, it is a list, but it doesn't matter much in this case as both arrays and lists are enumerable. If you want an empty array then you should use [||] or Array.empty.
The error you get is because your enumerable is of a generic type, i.e. the compiler doesn't know what type of elements that should go into your list/array. If you want a list of System.Object the following works (replace System.Object with the type of list you want, but you must specify something as a generic list is not allowed):