Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.
This repository was archived by the owner on Jan 12, 2024. It is now read-only.

Discriminated unions, Maybe? #406

@crazy4pi314

Description

@crazy4pi314

Is your feature request related to a problem? Please describe.
It would be really nice to have something like a maybe discriminated union. Say I have a function that I want to just return false to represent it failing, and if it succeeds then to return a different type (say a tuple).

Describe the solution you'd like
It would be nice to have something like Maybe<'T> where that's understood to be the type 'T or some other default type like bool to indicate something failed.

Describe alternatives you've considered
Not sure.

Additional context
I was working on refactoring some code in a Shor's algorithm sample and there are many steps there that can fail. I have split many of them out into their own functions and operations but that means I have to do something like this:

function MaybeFactorsFromPeriod(generator : Int, period : Int, number : Int) : (Bool, (Int, Int))
    {
        if (period % 2 == 0) {
            let halfPower = ExpModI(generator, period / 2, number);
            if (halfPower != number - 1) {
                let factor = MaxI(GreatestCommonDivisorI(halfPower - 1, number), GreatestCommonDivisorI(halfPower + 1, number));
                return (true, (factor, number / factor));
            } else {
                return (false, (1,1));
            }
        } else {
            return (false, (1,1));
        }
    }

Here I just have it return a tuple of a bool indicating if it worked, and a tuple of integers that are the derived factors if we got lucky on the period estimation part. I then have to unpack this in the main algorithm code, and I don't want to return (1,1) if it failed.

Metadata

Metadata

Assignees

Labels

area: languageChanges to the Q# languageduplicateThis issue or pull request already existsenhancementNew request or suggestion for an improvement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions