[prev in list] [next in list] [prev in thread] [next in thread] 

List:       haskell-beginners
Subject:    Re: [Haskell-beginners] filter by max length a list of lists with equivalent values
From:       Erlend Hamberg <ehamberg () gmail ! com>
Date:       2014-02-11 16:15:28
Message-ID: CA+G9OXmo2Gmt3K0V8CZZeRn55UCQpM+G7iddT+3V9muYxkHHVw () mail ! gmail ! com
[Download RAW message or body]

[Attachment #2 (multipart/alternative)]


Another way to do this would be to sort the sub lists according to what
they contain (the list heads) and then their length (to resolve ties).
You could then use nubBy with "(==) `on` head" to remove lists and only be
left with the longest lists. Since nub[By] keeps only the first occurrence
of each element when there are duplicates, "comparing length" is flipped -
meaning that longer lists come first. This gives us the following function:

    nubBy ((==) `on` head) . sortBy (comparing head <> flip (comparing
length)) . group

Where (<>) is from Data.Monoid. An explanation of using monoids to build
sorting combinators can be found in this reddit post [note that the author
uses (++) for (<>)]:
http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx

-- 
Erlend Hamberg
ehamberg@gmail.com

[Attachment #5 (text/html)]

<div dir="ltr"><div>Another way to do this would be to sort the sub lists according \
to what they contain (the list heads) and then their length (to resolve \
ties).</div><div>You could then use nubBy with &ldquo;(==) `on` head&rdquo; to remove \
lists and only be left with the longest lists. Since nub[By]&nbsp;<span \
style="color:rgb(0,0,0);font-family:sans-serif;font-size:13px;line-height:18.200000762939453px">keeps \
only the first occurrence of each element</span>&nbsp;when there are duplicates, \
&ldquo;comparing length&rdquo; is flipped &ndash; meaning that longer lists come \
first. This gives us the following function:&nbsp;</div>

<div><br></div>&nbsp; &nbsp; nubBy ((==) `on` head) . sortBy (comparing head &lt;&gt; \
flip (comparing length)) . group<br><div><br></div><div>Where (&lt;&gt;) is from \
Data.Monoid. An explanation of using monoids to build sorting combinators can be \
found in this reddit post [note that the author uses (++) for (&lt;&gt;)]:</div>

<div><a href="http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_program \
ming_language/c06adnx">http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx</a></div><div><br>


</div><div class="gmail_extra">-- <br>Erlend Hamberg<br><a \
href="mailto:ehamberg@gmail.com">ehamberg@gmail.com</a><br> </div></div>



_______________________________________________
Beginners mailing list
Beginners@haskell.org
http://www.haskell.org/mailman/listinfo/beginners


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic