Arithmetic operations between newtype Value = Value Number and Int

I have a newtype Value wrapper with a Number type. How do I perform operations with primitive types Number/ Int.

newtype Value = Value Number

derive newtype instance showValue :: Show Value

derive newtype instance eqValue :: Eq Value

derive newtype instance semiringValue :: Semiring Value

derive newtype instance ringValue :: Ring Value

instance semigroupValue :: Semigroup Value where append = (+)

instance monoidValue :: Monoid Value where mempty = zero

derive instance genericValue :: Generic Value _

instance decodeValue :: Decode Value where
decode = genericDecode $ defaultOptions { unwrapSingleConstructors = true }

valueMultiplier :: Value -> Int -> Value
valueMultiplier a b  = over Value (under a * b)

I have tried this but I am getting typesDoNotUnify error

Which types aren’t unifying?

By searching for Int -> Number, looks like you want to change the Int type to a Number type. You’ll likely get another error after that (Value isn’t Numer), but it’ll be one step closer to your goal.

Using toNumber seems to working for valueMultiplier :: Number -> Int -> Number. Thank you for suggesting.

However, I am not able to understand how to operate on the underlying Number type. I would request to provide an example of how to use Data.Newtype.unwrap.

1 Like

Hi @deepaktatineni, is the below what you were after? Sorry about the auxiliary go function but I wasn’t sure if maintaining the argument order as Value -> Int -> Value was important to you :slight_smile:

derive instance newtypeValue :: Newtype Value _

valueMultiplier :: Value -> Int -> Value
valueMultiplier = flip go
  where
    go :: Int -> Value -> Value
    go b = over Value (_ * toNumber b)
2 Likes