UPenn CIS 194 Homework 3: Code golf
go

First just a blanket statement about names. Since this is
a golfing challenge you should pick short names for
varibles, helper functions, etc. Of course, that makes
things less readable, but there are some conventions that
Haskellers follow:

go         - names a local helper function
xs, ys, zs - a list
(x:xs)     - xs is the tail of a list whose head is x
x'         - a value related to x


Some people complain about the heavy use of single letter
variable names in Haskell, but when used judiciously I think
it actually aids readability.

skips

You can perform filter, fst and unzip all in a single
list comprehension like this:

skips' n root@(_:xs) = [ x | (x,k) &lt;- zip root [0..], mod k n == 0] ++ ...


Also, note that you define devidedByIndex, but you only call it once.
In a situation like that you can always inline the definition where it is used,
and that's what we've done here by putting the mod k n ... expression
directly into the list comprehension.

localMaximum

You have three cases which return the same value, so just put the
last case first and use a default pattern for the others:

localMaxima (x:y:z:xz) = ...
localMaximum _ = []


Next, because we're golfing, you can avoid the otherwise clause and
duplicating the recursion call like this:

localMaxima (x:y:z:zs) = (if x &lt; y &amp;&amp; y &gt; z then [y] else []) ++ localMaximum ...


histogram

There are two sub-problems:


Computing the counts
Building the picture.


Let's start with #2, and say we have the counts in a list ns, i.e. the counts
for the example is [0,1,2,3,4,5,4,3,2].

A quick way to create the row for the k-th level is:

row k ns = [ if n &gt;= k then '*' else ' ' | n &lt;- ns ]


and then we just need to stack those lines together:

(row 9 ns) ++ "\n" ++ (row 8 ns) ++ "\n" ++ ... (row 1 ns) ++ "\n"


Perhaps this gives you some ideas on how to improve the code.

In your computeElements, again note that your helper count is only used once,
so for golfing purposes you can inline it:

countElements n = map (\x -&gt; length (elemIndices x n)) [0..9]


Also, compare:

elementIndices x n          - 16 non-space chars
[ y | y &lt;- n, y == x ]      - 13 non-space chars


Since you only interested in the length both will work.

Finally, whenever you have map (\x -&gt; ...) [...] it's the same as
a list comprehension:

map (\x -&gt; .A.) [.B.]  = [ .A. | x &lt;- [.B.]]


and the list comprehension is shorter by a few characters.

import ...

The exercise encourages you to look for standard library functions to help
you reduce your code size.

Here are some library functions which might be applicable to these problems:

tails :: [a] -&gt; [[a]]
sort :: Ord a =&gt; [a] -&gt; [a]
group :: Eq a =&gt; [a] -&gt; [[a]]
unlines :: [String] -&gt; String