gpt4 book ai didi

exception - 什么是一元错误?

转载 作者:行者123 更新时间:2023-12-02 23:31:21 25 4
gpt4 key购买 nike

我读到了一元错误作为返回值错误和异常的替代方案。有人可以解释并举例说明一元错误如何在命令式伪语言中工作(请不要提供功能示例)。

最佳答案

基本思想:

  • 成功输出或失败错误的概念被编码到类型中。
  • 此类型的值(或函数)可以组合成此类型的另一个值。不同成功类型的值可以组合,但它们必须具有相同的失败类型。
  • 一旦输出错误,其余的执行就会被短路以传播错误。

这是一个 C# 的工作示例:

<小时/>
// A discrimated union that can be either an error of type TError, 
// or a successful result of type TResult.
// IsError indicates which field has a valid value.
class Throws<TError, TResult>
{
public bool IsError;
public TError Error;
public TResult Result;

// Make a new successful reslt of type TResult.
public static Throws<TError, TResult> Success(TResult result)
{
Throws<TError, TResult> t = new Throws<TError, TResult>();
t.IsError = false;
t.Result = result;
return t;
}

// Make a new error of type TError.
public static Throws<TError, TResult> Fail(TError error)
{
Throws<TError, TResult> t = new Throws<TError, TResult>();
t.IsError = true;
t.Error = error;
return t;
}

// Composition.
public Throws<TError, TResultB> Bind<TResultB>(
Func<TResult, Throws<TError, TResultB>> f)
{
if (IsError)
{
// If this is an error, then we can short circuit the evaluation
return Throws<TError, TResultB>.Fail(Error);
}

// Otherwise, forward this result to the next computation.
return f(Result);
}
}

class Test
{
// num / demom
private static Throws<string, double> Div(double num, double denom)
{
if (denom == 0)
return Throws<string, double>.Fail("divide by zero");

return Throws<string, double>.Success(num / denom);
}

// Have the user enter a double.
private static Throws<string, double> ReadDouble(string name)
{
Console.Write("{0}: ", name);

string input = Console.ReadLine();
double result;
if (!double.TryParse(input, out result))
return Throws<string, double>.Fail(string.Format("can't parse {0}", name));

return Throws<string, double>.Success(result);
}

// Read two doubles and divide them to produce the result.
private static Throws<string, double> Interact()
{
return ReadDouble("numerator").Bind(num =>
ReadDouble("denominator").Bind(denom =>
Div(num, denom)));
}

public static void TestLoop()
{
while (true)
{
// Run a computation that asks the user for two numbers,
// divides them and then prints out the result.
Throws<string, double> t = Interact();

// Notice how the return type forces you to address the
// error if you want to get to the value.
if (t.IsError)
{
Console.WriteLine("Error: {0}", t.Error);
}
else
{
Console.WriteLine("Success: {0}", t.Result);
}
}
}
}

关于exception - 什么是一元错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13889299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com