user_9
user_9

Reputation: 55

Count number of slots in a template in haskell

I need to write a function, that will count the number of slots in a template. Such template ({})foo{}{} = 3. I have function prototype as

template :: Template -> Int
templatey (Template xs) =

And some helper functions:

data Slot = Slot
      deriving (Show, Eq)

data Template =
    Template [Either String Slot]
    deriving Eq

instance Show Template where
 show (Template xs) =   concat $ map f xs
    where f (Left x) = x
      f (Right x) = "{}"

data Def =
    Def [Template]
    deriving Eq

I wrote that:

temp = Template [Right Slot] And I guess I need to use map somehow to check if input template matches temp. But, I can't find the way how to do it. Any help is highly appreciated.

Upvotes: 1

Views: 227

Answers (1)

Sibi
Sibi

Reputation: 48766

Something like this should work:

template :: Template -> Int
template (Template xs) = sum $ map (\x -> either (\_ -> 0) (\_ -> 1) x) xs

In case you are seeing value of Right value constructor, you are returning 1 else 0. And finally you just sum it up to get the number of slots.

Or as Yuuri points out, this is more elegant:

template :: Template -> Int
template (Template xs) = sum $ map (either (const 0) (const 1)) xs

Or even this:

import Data.Either (rights)

template :: Template -> Int
template (Template xs) = length $ rights xs

Demo in ghci:

λ> template $ Template [Right Slot, Right Slot, Right Slot]
3
λ> template $ Template [Right Slot, Right Slot, Right Slot, Left "hi"]
3
λ> template $ Template [Right Slot, Right Slot, Right Slot, Left "hi", Right Slot]
4
λ> template $ Template []
0

Upvotes: 2

Related Questions