Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving Euler #31 in Haskell

Tags:

haskell

I compared my solution to the one published on haskell.org http://www.haskell.org/haskellwiki/Euler_problems/31_to_40 and don't know what to think of it. Is what I wrote so non-idiomatic, that an average haskell developer would immediately catapult my code to the moon?

main =
  print $ length $ split 200

split n = split' [200, 100, 50, 20, 10, 5, 2, 1] n
  where split' (1:[]) n = [take n $ repeat 1]
        split' (c:cs) n
          | n > c     = map (c:) (split' (c:cs) (n - c)) ++ split' cs n
          | n == c    = [[c]] ++ split' cs n
          | otherwise = split' cs n

Coming from "enterprisey" development I kind of value straight and dumb solutions, but on the other side maybe everybody can read one-liners just fine and I just need to pick up my game? Would you recommend compacting the code as an exercise, or is it just for hackers?

like image 392
vasily Avatar asked Aug 03 '14 18:08

vasily


1 Answers

As a general rule you can say that if there is any chance that others will read the code you write you should stay with painstakingly describing every last step in your code, even if it means that you have to write ten more lines than the fast and funky solution.

If you are writing code only for yourself, then you can do whatever you want but you have to keep in mind that you would probably like to understand the code you write when you find it on your hard drive after a long time.

Compacting it may be a useful thing to learn how to use Haskell's special features and bragging ("I solved that in one line!!") but otherwise one cannot overlook how important readability and maintainability are.

Another advantage for the longer code is that it is easier to debug if the code does not behave as expected because it's format resembles it's logical structure (if formatted correctly) and thus makes tracking errors much easier.

like image 160
ThreeFx Avatar answered Sep 28 '22 16:09

ThreeFx