Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add monadic functions to Result #3957

Merged
merged 4 commits into from
Dec 7, 2024

Conversation

stephenswat
Copy link
Member

@stephenswat stephenswat commented Dec 5, 2024

In order to make the Result type easier to use, this commit adds three new functions:

  • Result::value_or allows the user to obtain the value or a provided default value.
  • Result::transform models functorial mapping, allowing users to modify values inside results.
  • Result::and_then models monadic binding, allowing users to build complex chains of actions on results.

Implemented are lvalue and rvalue versions of these functions as well as tests.

image

Summary by CodeRabbit

  • New Features

    • Enhanced Result class with new methods for improved error handling and value transformation:
      • value_or: Retrieve valid value or default.
      • transform: Apply a function to the valid value.
      • and_then: Chain functions based on the result's validity.
  • Tests

    • Added comprehensive test cases to validate the new functionalities of the Result class, ensuring reliability and correctness:
      • ValueOrResult: Validates the value_or method.
      • TransformResult: Assesses the transform method.
      • AndThenResult: Evaluates the and_then method.

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

Enhancements to the Result class template in the Acts namespace have been made, introducing new member functions for improved error handling and value transformation. The new methods include value_or, transform, and and_then, each with both lvalue and rvalue versions. Additionally, the ResultTests.cpp file has been updated with new test cases to validate these functionalities, ensuring robust coverage for the class's operations.

Changes

File Change Summary
Core/include/Acts/Utilities/Result.hpp Added methods: value_or, transform, and_then (both lvalue and rvalue versions).
Tests/UnitTests/Core/Utilities/ResultTests.cpp Added test cases: ValueOrResult, TransformResult, AndThenResult to validate new methods.

Poem

In the realm of code, new powers arise,
Result now shines, a wondrous surprise.
With value_or and transform in tow,
Chaining with and_then, watch the magic flow!
Tests stand guard, ensuring all's right,
In the world of functions, a glorious sight! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the Component - Core Affects the Core module label Dec 5, 2024
@github-actions github-actions bot added this to the next milestone Dec 5, 2024
Copy link

github-actions bot commented Dec 5, 2024

📊: Physics performance monitoring for beb19d2

Full contents

physmon summary

Core/include/Acts/Utilities/Result.hpp Outdated Show resolved Hide resolved
Core/include/Acts/Utilities/Result.hpp Outdated Show resolved Hide resolved
@andiwand
Copy link
Contributor

andiwand commented Dec 6, 2024

one last question @stephenswat, what is a monad?

@stephenswat
Copy link
Member Author

stephenswat commented Dec 6, 2024

one last question @stephenswat, what is a monad?

A monad is just a monoid in the category of endofunctors, what's the problem?

More seriously, we need to understand a few concepts first.

A monoid is a set $S$ with some operator $\circ : S \times S \to S$ and some identity element $i : S$. The integers are a monoid under addition, so $S = \mathbb{Z}$, $\circ = +$, $i = 0$. The integers are also a monoid under multiplication with $i = 0$. Strings are a monoid under string concatenation with $i = ""$. And so forth.

A category is a set of objects connected via morphisms. In category theory there are many categories, but in programming we usually only deal with the category known as Type which contains all types. The morphisms in the category Type are functions.

A functor is something that maps objects and morphisms from one category onto another.

An example of a functor is std::optional. For any type T, std::optional maps T to std::optional<T>. Because std::optional maps Type to Type it is an endofunctor, i.e. it maps objects and morphisms from one category onto itself.

Now, this is where we can start talking about the operators in this PR. Note that value_or isn't really a categorical thing, but transform is very important and is more commonly known as fmap. Imaging that I have an object of type $T$ and a function $f : T \to U$. Remember that the std::optional functor takes T and creates std::optional<T>. But std::optional can also take f : T -> U and turn it into f : std::optional<T> -> std::optional<U>. So a functor transform types into new types, but it also transforms functions (morphisms) into new morphisms.

Now we know what a functor is, what an endofunctor is, and what a monoid is. Now we can talk about monads.

A monad is simply a functor (like std::optional) that has been extended with some additional tools. And the reason we need those tools is this. Imagine I have a function safeSqrt : int -> std::optional<double> which computes the square root of positive numbers, and returns an invalid result if the number is negative. Let's imagine I have an std::optional<int> already and I want to apply safeSqrt on it. I can run fmap safeSqrt on the value, but that turns my std::optional<int> into an std::optional<std::optional<double>> and that double-wrapped optional value is rather useless. What has happened here is that we have applied the functor std::optional to itself and received a new functor std::optional<std::optional>. See how that is similar to the definition of $\circ$ in the monoid?

Now, a monad is simply a functor equipped with the ability to "strip away" those unnecessary layers, i.e. to collapse the double wrapping of itself. This function is called join and is trivial to write:

std::optional<T> join(std::optional<std::optional<T>> v) {
    if (v.has_value()) {
        return *v;
    } else {
        return std::nullopt;
    }
}

Using join we can create the >>= operator, which here is called and_then which is where all the power from the monad comes from. In a Haskell like type system, we'd write the type of this as >>= :: m a -> (a -> m b) -> m b which means that, given 1. a std::optional<T>; and 2. a function that takes T and returns std::optional<U>, we can obtain a std::optional<U>. This allows us to chain functions together, like this:

std::optional<int> murderIfNotEven(int i) {
    if (i % 2 == 0) {
        return {i};
    } else {
        return std::nullopt;
    }
}

std::optional<double> safeSqrt(int i) {
    if (i >= 0) {
        return std::sqrt(static_cast<double>(i));
    } else {
        return std::nullopt;
    }
}

...

// returns std::nullopt, because one of the operations "fails"
std::optional<double> a = murderIfNotEven(5).and_then(safeSqrt);
// also returns std::nullopt
std::optional<double> b = murderIfNotEven(-2).and_then(safeSqrt);
// returns 1.41
std::optional<double> c = murderIfNotEven(2).and_then(safeSqrt);

Note that std::optional is just one monad; std::vector is a monad, as is Result and std::variant.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
Core/include/Acts/Utilities/Result.hpp (2)

178-212: Correct implementation of value_or, hmm yes.

Handle references and move semantics properly, this implementation does. A small documentation improvement suggest I must:

-///e@param[in] v The default value to use if no valid value exists.
+/// @param[in] v The default value to use if no valid value exists.

258-314: Strong with the Force, this monadic implementation is.

Follow the monad laws, it does. But improve the error message, we can:

-                  "bind must take a callable with the same error type");
+                  "bind must take a callable returning Result with the same error type");
Tests/UnitTests/Core/Utilities/ResultTests.cpp (1)

371-389: More test cases, we should add.

Good start this is, but strengthen the tests with these cases, we must:

  • Test transformation that changes type (e.g., int to string)
  • Test with throwing transformations
  • Test with transformations that return references
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 093fa86 and 8310bf3.

📒 Files selected for processing (2)
  • Core/include/Acts/Utilities/Result.hpp (2 hunks)
  • Tests/UnitTests/Core/Utilities/ResultTests.cpp (1 hunks)
🔇 Additional comments (3)
Core/include/Acts/Utilities/Result.hpp (1)

214-256: Wise implementation of transform, this is.

Follow the functor laws, it does. Handle both lvalue and rvalue cases correctly, it does. Type safety through concepts, it maintains.

Tests/UnitTests/Core/Utilities/ResultTests.cpp (2)

336-369: Thorough test coverage, you have achieved.

Test both success and failure paths, you do. Verify reference semantics correctly, you have. Miss no edge cases, you did.


391-423: Complete and balanced, these tests are.

Test all paths of the monad, you do. Handle errors with wisdom, you have. Verify type changes correctly, you did.

In order to make the `Result` type easier to use, this commit adds three
new functions:

 * `Result::value_or` allows the user to obtain the value or a provided
   default value.
 * `Result::transform` models functorial mapping, allowing users to
   modify values inside results.
 * `Result::and_then` models monadic binding, allowing users to build
   complex chains of actions on results.

Implemented are lvalue and rvalue versions of these functions as well as
tests.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
Core/include/Acts/Utilities/Result.hpp (1)

258-314: Powerful monadic binding, implemented you have!

Follow the sacred monad laws, your implementation does:

  • Left identity: return a >>= f ≡ f a
  • Right identity: m >>= return ≡ m
  • Associativity: (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)

Yet, improve the error message in static_assert, we could.

-                 "bind must take a callable with the same error type");
+                 "and_then requires callable returning Result with matching error type");
Tests/UnitTests/Core/Utilities/ResultTests.cpp (1)

371-389: More test cases, add we should.

Good foundation laid, you have. Yet enhance we could with:

  • Complex transformations testing
  • Chain of transformations
  • Type-changing transformations
// Add these test cases
auto f2 = [](int x) { return std::to_string(x); };  // type-changing
auto f3 = [](int x) { return x < 0 ? Result::failure(MyError::Failure) : Result::success(x); };  // error-producing

BOOST_CHECK(Result::success(5).transform(f1).transform(f2).ok());
BOOST_CHECK_EQUAL(Result::success(5).transform(f1).transform(f2).value(), "10");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8310bf3 and 1ee5965.

📒 Files selected for processing (2)
  • Core/include/Acts/Utilities/Result.hpp (2 hunks)
  • Tests/UnitTests/Core/Utilities/ResultTests.cpp (1 hunks)
🔇 Additional comments (4)
Core/include/Acts/Utilities/Result.hpp (2)

178-212: Wise implementation of value_or, it is! Hmmmm.

Handle both lvalue and rvalue cases correctly, you do. Type safety through requires-clause, maintain you have. Documentation, thorough it is.


214-256: Strong with the Force, this transform implementation is!

Follow the ancient functor laws, you do:

  • Identity preservation: f(x) -> x, maintain you do
  • Composition: g(f(x)) -> (g ∘ f)(x), respect you have
  • Error propagation: handle with grace, you do

Well implemented, this is!

Tests/UnitTests/Core/Utilities/ResultTests.cpp (2)

336-369: Thorough tests for value_or, written you have!

Cover all cases, your tests do:

  • Success and failure paths
  • Reference handling
  • Value preservation

391-423: Well tested, the monadic binding is!

Cover the essential cases, your tests do:

  • Success and failure paths
  • Error propagation
  • Basic chaining

Copy link
Contributor

@andiwand andiwand left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍

@stephenswat
Copy link
Member Author

What on earth is this CI failure? 🤔

@andiwand
Copy link
Contributor

andiwand commented Dec 7, 2024

never seen this before. maybe @benjaminhuth @paulgessinger ?

@stephenswat
Copy link
Member Author

Should be solved by #3967.

Copy link

sonarcloud bot commented Dec 7, 2024

@kodiakhq kodiakhq bot merged commit 9067679 into acts-project:main Dec 7, 2024
42 checks passed
@github-actions github-actions bot removed the automerge label Dec 7, 2024
@acts-project-service
Copy link
Collaborator

🔴 Athena integration test results [9067679]

Build job with this PR failed!

Please investigate the build job for the pipeline!

@acts-project-service acts-project-service added the Breaks Athena build This PR breaks the Athena build label Dec 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Breaks Athena build This PR breaks the Athena build Component - Core Affects the Core module
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants