Say I have something silly like this:
data SomeType
= Unary Int
| Associative SomeType
| Binary SomeType SomeType
some_func :: SomeType -> Int
some_func s =
case s of
Unary n -> n
Associative s1 -> some_func s1
Binary s1 s2 -> some_func s1 + some_func s2
Here some_func will look through all SomeTypes in a given SomeType and sum up the Ints of all Unary data constructors. SomeType is a recursive data type.
In these pattern matches I'm repeating some_func s1
. Is there a way to use @, when, let or anything else to declare sf1 = some_func s1
and use it in both? Something like this:
data SomeType
= Unary Int
| Associative SomeType
| Binary SomeType SomeType
some_func :: SomeType -> Int
some_func s =
case s of
Unary n -> n
Associative s1 -> sf1
Binary s1 s2 -> sf1 + sf2
where
sf1 = some_func s1
sf2 = some_func s2
The problem here is that s1 and s2 are only known in the block after ->
and sf1 can't be calculated.
This doesn't answer the question but might solve the problem:
{-# LANGUAGE DeriveFoldable #-}
module SomeType where
import Data.Foldable as F
data SomeType a
= Unary a
| Associative (SomeType a)
| Binary (SomeType a) (SomeType a)
deriving (Foldable)
some_func :: SomeType Int -> Int
some_func = F.foldl1 (+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With