简体   繁体   中英

Haskell :How to define an instance of the constructor class Foldable for the constructor

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 want LB xs , not LB [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 are v copies of i , rather than always incorporating i exactly once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM