0

There have been some major changes in base library, so I'm wondering whether today idiomatic solution would involve fmap, Maybe, Monoid, First, Foldable and maybe other classes.

I figured I would need to fold a complex structure of a Monoid with zip [1..], First, a -> Bool and Maybe, but couldn't find obvious way to compose these things together.

Also, I suspect most of this code is in libraries. I'm just not sure whether (or how many) newtype wrappers would I need to compose classes to get a structure I need.

sclv
  • 38,665
  • 7
  • 99
  • 204
sevo
  • 4,559
  • 1
  • 15
  • 31

1 Answers1

0

Zeta's comment is right. You can just call toList and then find the element in that. But supposing we didn't want to do this, how could we do it using monoids?

Here's one approach

data FirstTrue = FT Int Bool deriving Show

instance Monoid FirstTrue where
   mempty = FT 0 False
   FT n b `mappend` ~(FT n1 b1)
      | b = FT n True
      | b1 = FT (n + n1) True
      | otherwise = FT (n + n1) False

findIndex p t = let (FT i b) = foldMap (\x -> FT 1 (p x)) t
                in if b then Just i else Nothing

I don't think that you can do it in this generality and build it just out of Foldable and existing Monoid instances, as the types of compositions we have don't let you "cross over" the logic from the two conjoined monoid types (here the Count monoid and the Any monoid).

sclv
  • 38,665
  • 7
  • 99
  • 204