Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter Syntax For Cases In Haskell?

Tags:

haskell

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.

like image 426
Aram Kocharyan Avatar asked Nov 30 '22 14:11

Aram Kocharyan


1 Answers

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 (+)
like image 121
phyrex1an Avatar answered Dec 12 '22 04:12

phyrex1an