user1206480
user1206480

Reputation: 1858

Using match expression in nested for loop

I seem to lose intellisense within the query of the innermost for loop, which is leading me to believe that I am writing bad code. It appears to be an issue with the match statement. When I try to match by simply capturing the value everything seems to work. When I try to match by comparing values the code seems to break. Here is the code:

let createOrderFromStdOrder () =

    // retrieve standard orders
    let stdOrders = 
        Queries.retrieveStdOrders null |> Seq.toList

    // retrieve orders
    let orders = Queries.retrieveOrders null |> Seq.toList

    // current date
    let curDate = DateTime.Now

    // iterate and create order
    for i in stdOrders do

        let validDates = MyUtil.stdDeadlineCheck i

        // process standard order
        let orderDate = 
            if not validDates.IsEmpty then
                let daysOfWeek = 
                    query{
                        for row in validDates do
                        sortBy row
                        take 2
                    }

                for j in daysOfWeek do
                    match j with
                    | c -> // this seems to work
                        let order =
                            query{
                                for o in orders do
                                where(o.Works = i.Works) // and I get dot intellisense o and i
                            }

but if I try to match like this it seems to break:

                for j in daysOfWeek do
                    match j with
                    | DateTime.Now.DayOfWeek -> // this does not work
                        let order =
                            query{
                                for o in orders do
                                where(o.NOTHING = i.Works) // NO dot intellisense on o
                            }

I suspect this may have something to do with the nesting. How can I correct this?

Upvotes: 0

Views: 267

Answers (1)

Tarmil
Tarmil

Reputation: 11362

Pattern matching can only test equality with constants, not values such as DateTime.Now.DayOfWeek. The reason is that it would make it ambiguous when the value is a simple variable name, because variables in a pattern are used to bind whatever value is at this position to a name, rather than comparing it to an existing variable:

match j with
| x ->
    // in here, x is equal to j.

In your specific case, you can just use if:

for j in daysOfWeek do
    if j = DateTime.Now.DayOfWeek then
        let order = // ...

But if, in a more complex case, you want to compare with an inner pattern, you can use a guard:

match someRecord with
| { someField = d } when d = DateTime.Now.DayOfWeek ->
    let order = // ...

Upvotes: 2

Related Questions