Couldn't match type ‘Numeric 10’ with ‘()’ Cannot understand the message

Hello! I’m trying to run a command in a function that looks something like this:
(Correct keys are generated but I’m replacing in the example with *_id just for simplicity.)

decimal_values <- forA object.child_ids
  \child_id -> do
    (_, child) <- fetchByKey @ChildContract child_id
    DA.Optional.whenSome(DA.List.elemIndex resource_id child.resource_ids)
      \_ -> do
        (_, resource) <- fetchByKey @ResourceContract resource_id
        return resource.decimal_value
    return 0.0
return (sum decimal_values)

I get the error:

• Couldn't match type ‘Numeric 10’ with ‘()’
  arising from a functional dependency between:
  constraint ‘DA.Internal.Record.HasField
  "decimal_value" ResourceContract ()’
  arising from a use of ‘getField’
  instance ‘DA.Internal.Record.HasField
  "decimal_value" ResourceContract Decimal’
  at <no location info>

I’ve been stuck at this for a little while and I’m unsure what is going on. Can I ask for some guidance on this please? Thank you!

Basically what I’m trying to do is to query a few levels down and check whether certain resource exists, and if it does, get a decimal value from it and aggregate those decimal values across all the resources we find.

1 Like

whenSome has type Applicative m => Optional a -> (a -> m ()) -> m (). In your case m = Update. The issue is that the function you’re passing to whenSome returns a Numeric 10 rather than ().

One important point here is that confusingly return does not correspond to a return in an imperative language like Javascript. It’s a function Applicative m => a -> m a which lifts a value but execution continues afterwards. I usually tend to prefer pure which is equivalent but not as misleading.

In your example, you can use an if instead to fix your code:

if DA.List.elem resource_id child.resource_ids
  then do
    (_, resource) <- fetchByKey @ResourceContract resource_id
    return resource.decimal_value
  else
    return (sum decimal_values)
1 Like

Great to know, thank you! Didn’t realize that’s how whenSome worked.