Count number of slots in a template in haskell -


i need write function, count number of slots in template. such template ({})foo{}{} = 3. have function prototype

template :: template -> int templatey (template xs) = 

and helper functions:

data slot = slot       deriving (show, eq)  data template =     template [either string slot]     deriving eq  instance show template  show (template xs) =   concat $ map f xs     f (left x) = x       f (right x) = "{}"  data def =     def [template]     deriving eq 

i wrote that:

temp = template [right slot] , guess need use map somehow check if input template matches temp. but, can't find way how it. highly appreciated.

something should work:

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

in case seeing value of right value constructor, returning 1 else 0. , sum number of slots.

or yuuri points out, more elegant:

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

or 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 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -