简体   繁体   中英

How to use F#'s headOrDefault on an empty array?

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, ie 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):

let emptyarr:System.Object list = []
let res = query {
    for e in emptyarr do
    select e
    headOrDefault
}
System.Console.WriteLine("{0}", (res = null))

我认为最好的方法是let arr = [] : obj list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM