I've just started Haskell and after reading Foldable documentation I'm trying to Define an instance of the constructor class Foldable for the constructor ListBag where :
newtype ListBag a = LB [(a,Int)] deriving (Show,Eq)
To this aim, I have binary function f that applies to first elements of my multiset. and this is what I have tried:
instance Foldable ListBag where
foldr f z (LB[]) = 0
foldr f z (LB [x]) = f i z where (i,_) = x
foldr f z (LB [x : xs]) = f i foldr f z (LB[xs]) where (i,_) = x
which is not correct but best I could do...
any idea how to correct it?
(Yes, the f
function should be applied ignoring multiplicities.)
The pattern
[x]
matches a list with one element, just like you were hoping. But the pattern[x : xs]
also matches a list with one element -- that must itself be a list, and non-empty. You want(x : xs)
instead. (Similarly, in that line, you wantLB xs
, notLB [xs]
, as the latter attempts to wrap an extra layer of lists around the tail of the list.)Additionally, I suspect you will be happier with an instance that, when it sees
(i,v)
, pretends there arev
copies ofi
, rather than always incorporatingi
exactly once.