core icon indicating copy to clipboard operation
core copied to clipboard

[feature request] add error-awared functions like: `makei_error`, `map_error`

Open tonyfettes opened this issue 1 year ago • 2 comments

It's often the case when I want to construct an Array[T] or FixedArray[T] from a function that can raise error. For example, I want to construct a Tensor from a Json value:

fn main {
  match json {
    Json::Number(x) => Tensor::new(x)
    Json::Array(xs) => {
      let value : FixedArray[Tensor] = FixedArray::makei(xs.length(), fn(i) {
        Tensor::from_json!(xs[i], @json.add_index(path, i))
      })
      Tensor::stack(value)
    }
    _ => raise @json.JsonDecodeError((path, "Expected an array"))
  }
}

For now it is not possible to achieve this, since FixedArray::makei require the callback to be error-free.

tonyfettes avatar Sep 21 '24 04:09 tonyfettes

@tonyfettes Maybe the functions of all core module have to add the error feature. But i wish you do not use error feature in you code. Because this feature influences all related code if you use it. Just like now scene you face.

htoooth avatar Sep 23 '24 06:09 htoooth

let value : FixedArray[Tensor] = FixedArray::makei(xs.length(), fn(i) {
        Tensor::from_json!(xs[i], @json.add_index(path, i))
      })
Tensor::stack(value)

Note you work around this using for .. in , I am hestitant to add such API since eventually want our map to propagate callbacks with Error something like this:

map[A](self : Array[A], f : (A) ->B!_) -> Array[B]!_ // when call back has error, result has error

bobzhang avatar Sep 25 '24 02:09 bobzhang

let value : FixedArray[Tensor] = FixedArray::makei(xs.length(), fn(i) {
        Tensor::from_json!(xs[i], @json.add_index(path, i))
      })
Tensor::stack(value)

Note you work around this using for .. in , I am hestitant to add such API since eventually want our map to propagate callbacks with Error something like this:

map[A](self : Array[A], f : (A) ->B!_) -> Array[B]!_ // when call back has error, result has error

The function type (A) -> B is incompatitble with (A) -> B!Error at now. Is !_ here a syntax that imply that the error type can be unused in the function (which will be reported as an error currently)?

FlammeShadow avatar Jan 23 '25 09:01 FlammeShadow

We will implement effect polymorphism in the near future.

peter-jerry-ye avatar Apr 11 '25 08:04 peter-jerry-ye