{"id":13415216,"url":"https://github.com/atifaziz/Optuple","last_synced_at":"2025-03-14T22:33:04.302Z","repository":{"id":66141550,"uuid":"147307115","full_name":"atifaziz/Optuple","owner":"atifaziz","description":".NET Standard Library for giving (bool, T) Option-like semantics","archived":false,"fork":false,"pushed_at":"2019-08-29T07:56:49.000Z","size":69,"stargazers_count":29,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-29T11:41:46.510Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/Optuple/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/atifaziz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"COPYING.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2018-09-04T07:39:35.000Z","updated_at":"2024-07-17T11:06:35.000Z","dependencies_parsed_at":"2023-02-24T08:30:19.204Z","dependency_job_id":null,"html_url":"https://github.com/atifaziz/Optuple","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atifaziz%2FOptuple","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atifaziz%2FOptuple/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atifaziz%2FOptuple/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atifaziz%2FOptuple/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/atifaziz","download_url":"https://codeload.github.com/atifaziz/Optuple/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243658057,"owners_count":20326459,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T21:00:45.271Z","updated_at":"2025-03-14T22:33:04.292Z","avatar_url":"https://github.com/atifaziz.png","language":"C#","readme":"# Optuple\n\nOptuple is a .NET Standard library that enables a tuple of Boolean and some\ntype (`T`), i.e. `(bool, T)`, to have the same semantics as an option type\nfound in most functional languages.\n\nAn option type is a discriminated union that either represents the absence of\na value (_none_) or the value that's present (_some_). For example, F# has\nsuch a type that is defined as:\n\n```f#\ntype Option\u003cT\u003e = | None | Some of T\n```\n\nOptuple, however, does not define any such type. Instead it primarily supplies\nextension methods for any `(bool, T)` (like `Match`, `Map` and more) to be\ntreated like an option type. Suppose a value `x` of type `T`, then\n`(true, x)` will be treated like `Some x` and `(false, _)` will\nbe treated like `None`. Note that in the _none case_, when the first\nelement is `false`, Optuple completely ignores and discards the second\nelement.\n\nA library that wants to expose optional values needs no dependency on Optuple.\nIt can just expose `(bool, T)` for some type `T`. The client of the library\ncan use Optuple independently to get \u0026ldquo;optional semantics\u0026rdquo;.\n\n\n## Usage\n\n### Using the library\n\nTo use Optuple simply import the following namespace:\n\n```c#\nusing Optuple;\n```\n\nAn auxiliary namespace is also provided:\n\n```c#\nusing Optuple.Linq; // LINQ query syntax support\n```\n\n\n### Creating optional values\n\nThe most basic way to create optional values is to use the static `Option`\nclass:\n\n```c#\nvar none = Option.None\u003cint\u003e();\nvar some = Option.Some(42);\n```\n\nSimilarly, a more general extension method is provided, allowing a specified\npredicate:\n\n```c#\nstring str = \"foo\";\nvar none = Option.SomeWhen(str, s =\u003e s == \"bar\"); // Return None if predicate is violated\nvar none = Option.NoneWhen(str, s =\u003e s == \"foo\"); // Return None if predicate is satisfied\n```\n\nClearly, optional values are conceptually quite similar to nullables. Hence, a\nmethod is provided to convert a nullable into an optional value:\n\n```c#\nint? nullableWithoutValue = null;\nint? nullableWithValue = 2;\nvar none = nullableWithoutValue.ToOption();\nvar some = nullableWithValue.ToOption();\n```\n\n### Retrieving values\n\nWhen retrieving values, Optuple forces you to consider both cases (that is\nif a value is present or not).\n\nFirstly, it is possible to check if a value is actually present:\n\n```c#\nvar isSome = option.IsSome(); //returns true if a value is present\nvar isNone = option.IsNone(); //returns true if a value is not present\n```\n\nIf you want to check if an option `option` satisfies some predicate, you can\nuse the`Exists` method.\n\n```c#\nvar isGreaterThanHundred = option.Exists(val =\u003e val \u003e 100);\n```\n\nThe most basic way to retrieve a value from an `Option\u003cT\u003e` is the following:\n\n```c#\n// Returns the value if present, or otherwise an alternative value (42)\nvar value = option.Or(42);\n```\n\nSimilarly, the `OrDefault` function simply retrieves the default value for\na given type:\n\n```c#\nvar none = Option.None\u003cint\u003e();\nvar value = none.OrDefault(); // Value 0\n```\n\n```c#\nvar none = Option.None\u003cstring\u003e();\nvar value = none.OrDefault(); // null\n```\n\n\nIn more elaborate scenarios, the `Match` method evaluates a specified\nfunction:\n\n```c#\n// Evaluates one of the provided functions and returns the result\nvar value = option.Match(x =\u003e x + 1, () =\u003e 42);\n\n// Or written in a more functional style (pattern matching)\nvar value = option.Match(\n  some: x =\u003e x + 1,\n  none: () =\u003e 42\n);\n```\n\nThere is a similar `Match` function to simply induce side-effects:\n\n```c#\n// Evaluates one of the provided actions\noption.Match(x =\u003e Console.WriteLine(x), () =\u003e Console.WriteLine(42));\n\n// Or pattern matching style as before\noption.Match(\n  some: x =\u003e Console.WriteLine(x),\n  none: () =\u003e Console.WriteLine(42)\n);\n```\n\n### Transforming and filtering values\n\nA few extension methods are provided to safely manipulate optional values.\n\nThe `Map` function transforms the inner value of an option. If no value is\npresent none is simply propagated:\n\n```c#\nvar none = Option.None\u003cint\u003e();\nvar stillNone = none.Map(x =\u003e x + 10);\n\nvar some = Option.Some(42);\nvar somePlus10 = some.Map(x =\u003e x + 10);\n```\n\nFinally, it is possible to perform filtering. The `Filter` function returns\nnone, if the specified predicate is not satisfied. If the option is already\nnone, it is simply returned as is:\n\n```c#\nvar none = Option.None\u003cint\u003e();\nvar stillNone = none.Filter(x =\u003e x \u003e 10);\n\nvar some = Option.Some(10);\nvar stillSome = some.Filter(x =\u003e x == 10);\nvar none = some.Filter(x =\u003e x != 10);\n```\n\n### Helpers as global methods\n\nIf you [statically import][static-using] `OptionModule`:\n\n```c#\nusing static Optuple.OptionModule;\n```\n\nit will make the following common methods available for use without type\nqualification:\n\n- `Some`\n- `None\u003c\u003e`\n- `SomeWhen`\n- `NoneWhen`\n\nThis permits you to, for example, simply write `Some(42)` and `None\u003cint\u003e()`\ninstead of `Option.Some(42)` and `None\u003cint\u003e()`, respectively.\n\n### Enumerating options\n\n[comment]: # (Move somewhere?!)\n\nAlthough options deliberately don't act as enumerables, you can easily convert\nan option to an enumerable by calling the `ToEnumerable()` method:\n\n```c#\nvar enumerable = option.ToEnumerable();\n```\n\nBy importing the `Optuple.Collections` namespace, you also get the following\nextension methods for sequences (`IEnumerable\u003c\u003e`) that are like their LINQ\ncounterparts but return an option:\n\n- `FirstOrNone`: like [`FirstOrDefault`][FirstOrDefault] but returns an option\n- `LastOrNone`: like [`LastOrDefault`][LastOrDefault] but returns an option\n- `SingleOrNone`: like [`SingleOrDefault`][SingleOrDefault] but returns an option\n\n[FirstOrDefault]:  https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault\n[LastOrDefault]:   https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.lastordefault\n[SingleOrDefault]: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault\n\nThen there is:\n\n- `Filter`, which given a sequence of options, will return a sequence of _x_\n  values from those options in the original sequence that are _some x_.\n- `ListAll`, which given a sequence of options, will return _some list of\n  x_ if all options in the original sequence are _some x_; otherwise it returns\n  _none list_.\n\n### Working with LINQ query syntax\n\nOptuple supports LINQ query syntax, to make the above transformations\nsomewhat cleaner.\n\nTo use LINQ query syntax you must import the following namespace:\n\n```c#\nusing Optuple.Linq;\n```\n\nThis allows you to do fancy stuff such as:\n\n```c#\nvar personWithGreenHair =\n  from person in FindPersonById(10)\n  from hairstyle in GetHairstyle(person)\n  from color in ParseStringToColor(\"green\")\n  where hairstyle.Color == color\n  select person;\n```\n\nIn general, this closely resembles a sequence of calls to `FlatMap` and\n`Filter`. However, using query syntax can be a lot easier to read in complex\ncases.\n\n### Equivalence and comparison\n\nTwo optional values are equal if the following is satisfied:\n\n* The two options have the same type\n* Both are none, both contain null values, or the contained values are equal\n\n\n---\n\nCredit: A large portion of this documentation was dervied from that of the\nproject [Optional]. Thank you, [Nils L\u0026uuml;ck][nlkl]!\n\n\n[Optional]: https://www.nuget.org/packages/Optional/\n[nlkl]: https://github.com/nlkl\n[static-using]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static\n","funding_links":[],"categories":["Functional programming","函数式编程"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatifaziz%2FOptuple","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatifaziz%2FOptuple","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatifaziz%2FOptuple/lists"}