Skip to content

How to iterate over a list of strings and execute a method for each string as long as an error occurs #1261

Closed

Description

@dirkil

Suppose you have a method Fin<Unit> Calc(string input) and a list of strings that you want to call Calc on. Calc can fail and when that happens you want to stop iterating and return the error. I know you can do it with a foreach loop like that:

public Fin<Unit> Process(List<string> inputValues)
{
        foreach (var input in inputValues)
        {
            var result = Calc(input);
            if (result.IsFail)
                return result;
        }

        return Unit.Default;
}

This approach is rather non-functional and not in the style of LanguageExt. Is there a more functional version that someone can recommend?

Activity

  1. olegdunkan commented on Oct 20, 2023

    @olegdunkan

    public Fin<IEnumerable<Unit>> Process(List<string> values) => values.Select(Calc).Traverse(x => x);

  2. Repository owner locked and limited conversation to collaborators on Oct 20, 2023
  3. converted this issue into a discussion #1262 on Oct 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions