[L03 State] Refining firstRepeat? (SPOILERS)

67 views
Skip to first unread message

David Tchepak

unread,
Feb 22, 2013, 6:34:16 AM2/22/13
to haskell-exercises
I'm trying to refine my attempt at firstRepeat.

I started with:

firstRepeat ::
  Ord a =>
  List a
  -> Optional a
firstRepeat =
  flip eval S.empty 
      . findM (\x -> State (\s -> (x `S.member` s, x `S.insert` s)))

(where S is Data.Set)

I noticed I am taking (S.member, S.insert) and applying `x` and `s` to both parts of the tuple, and I was interested in seeing if there was a way to express this. I looked at using (&&&) from Control.Arrow, which gives me:

  (b -> c) -> (b -> d) -> b -> (c,d)    -- specialised to (->)

So I can get this:

    flip eval S.empty
        . findM (\x -> State $ S.member x &&& S.insert x)

Is there a nice way to refine this, getting rid of the explicit `x` reference?

Cheers,
David

Tony Morris

unread,
Feb 22, 2013, 1:03:12 PM2/22/13
to haskell-...@googlegroups.com
> --
> You received this message because you are subscribed to the Google
> Groups "haskell-exercises" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to haskell-exerci...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
Try this.

State . liftA2 (&&&) S.member S.insert

--
Tony Morris
http://tmorris.net/

David Tchepak

unread,
Feb 22, 2013, 6:06:17 PM2/22/13
to haskell-exercises
That's awesome. Thanks!
Reply all
Reply to author
Forward
0 new messages