take until duplicate

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

take until duplicate

Mike Houghton
I’m looking at how to take from a list until a duplicate is found.
e.g.

takeUntilDup [1,2,3,4,3] = [1,2,3,4]

I found this implementation

takeUntilDup  = foldr (\x r -> x : takeWhile (/= x) r) []

It works but I can’t see how!!?
The accumulated result is built up in r so with input  [1,2,3,4,3] then,  at the point when r = [1, 2, 3, 4],  the fold is about to use the number 3. i.e. it does takeWhile (/=3) [1,2,3,4]  which gives [1,2]

Please, how does this work?

Thanks
Mike
.
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: take until duplicate

Mike Houghton
duh! I tried

scanr  (\x acc -> x : takeWhile (/= x) acc) [] [1,2,3,4,5,3]

which gives
[[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5,3],[5,3],[3],[]]

which kind of makes sense.

M



> On 24 Sep 2017, at 20:08, mike h <[hidden email]> wrote:
>
> I’m looking at how to take from a list until a duplicate is found.
> e.g.
>
> takeUntilDup [1,2,3,4,3] = [1,2,3,4]
>
> I found this implementation
>
> takeUntilDup  = foldr (\x r -> x : takeWhile (/= x) r) []
>
> It works but I can’t see how!!?
> The accumulated result is built up in r so with input  [1,2,3,4,3] then,  at the point when r = [1, 2, 3, 4],  the fold is about to use the number 3. i.e. it does takeWhile (/=3) [1,2,3,4]  which gives [1,2]
>
> Please, how does this work?
>
> Thanks
> Mike


.
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: take until duplicate

Francesco Ariis
On Sun, Sep 24, 2017 at 08:31:46PM +0100, mike h wrote:

> duh! I tried
>
> scanr  (\x acc -> x : takeWhile (/= x) acc) [] [1,2,3,4,5,3]
>
> which gives
> [[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5,3],[5,3],[3],[]]
>
> which kind of makes sense.
>
> M

Well done, I find that :step and :show bindings are useful too
in these cases.
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners