TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Fun with a Functional Programming Interview Question

11 pointsby amscottiover 4 years ago

7 comments

dirktover 4 years ago
Haskell in REPL:<p><pre><code> Prelude&gt; :m Data.List Prelude Data.List&gt; let f xs = [(head ys, length ys) | ys &lt;- group xs] Prelude Data.List&gt; f &quot;aaaabbbcca&quot; [(&#x27;a&#x27;,4),(&#x27;b&#x27;,3),(&#x27;c&#x27;,2),(&#x27;a&#x27;,1)] </code></pre> Of course using the &quot;group&quot; function instead of programming it myself is cheating a bit ...
d_t_wover 4 years ago
#(mapv (juxt (comp str first) count) (partition-by identity %))
al2o3crover 4 years ago
Surprising that F# doesn&#x27;t have a &quot;chunkBy&quot; function for sequences; it makes the solution in Elixir vastly more readable than the version in the article:<p><pre><code> &quot;aaaabbbcca&quot; |&gt; String.codepoints() |&gt; Enum.chunk_by(&amp; &amp;1) |&gt; Enum.map(&amp;{hd(&amp;1), length(&amp;1)})</code></pre>
评论 #26052325 未加载
zzo38computerover 4 years ago
I did it this way:<p><pre><code> map (head &amp;&amp;&amp; length) . group </code></pre> (Although in an actual full program, there would be other considerations (what considerations those are depends on the program being written), and in a full program I probably would not be using Haskell, but rather C.)
homicover 4 years ago
I attempted this as a Haskell beginner. Positive it can be improved upon.<p><pre><code> runLengthEncode :: String -&gt; [(Char, Int)] runLengthEncode [] = [] runLengthEncode input = let chFirst = head input zipped = zip input $ chFirst : input in rle zipped (chFirst, 0) where rle :: [(Char, Char)] -&gt; (Char, Int) -&gt; [(Char, Int)] rle [] (ch, count) = [(ch, count)] rle ((ch1, ch2) : cs) (ch, count) = if ch1 == ch2 then rle cs (ch1, count + 1) else (ch2, count) : rle cs (ch1, 1)</code></pre>
riwskyover 4 years ago
meanwhile python be out here like:<p><pre><code> [(m.group(1), len(m.group())) for m in re.finditer(r&quot;([a-z])\1*&quot;, “aaaabbbcca&quot;)</code></pre>
评论 #26053447 未加载
badhabitover 4 years ago
newlisp:<p>(set &#x27;L &#x27;()) (dolist (s (explode &quot;aaaabbbcca&quot;)) (if (!= (ref-all s L) &#x27;((0 0))) (push (list s 1) L) (inc (L 0 1)))) (print (reverse L))