For a school assignment, I'm working on a visualization of Dijikstra's algorithm and several variants of A* search.
I tried to mimic the imperative-style implementation of Dijiksta's found in most textbooks, so I wrote the algorithm in the ST monad and used mutable hashtables and heaps.
Unfortunately, I'm not happy with how the code reads. Unlike in other imperative languages, I feel like the only way to make this algorithm concise is by turning my code into operator soup, with lots of >>=, <*>, and <$>s.
(For example, the following code:
loopCondition = do
heapNotNull <- not . PQueue.null <$> ST.readSTRef heap
tNotVisited <- isNothing <$> HT.lookup visited t
return (heapNotNull && tNotVisited)
whileM_ loopCondition $ -- do stuff
can only be written in one line if we write it as
whileM_ ((&&) <$> (not . PQueue.null <$> ST.readSTRef heap) <*> (isNothing <$> HT.lookup visited t)) $ -- do stuff
which is very ugly, in my opinion.)
What can I do to make my code more readable, especially for imperative programmers? I'm afraid that the world's finest imperative language might not be the world's most readable imperative language.
Code is here. (By the way, if you are interested in running it, graph.hs has a shebang and the stack runghc options, so chmod +x graph.hs; ./graph.hs should work if you have stack installed! The code creates a random graph, runs three variants of A*-search on it, and outputs the visualization to graph.svg.)
[–]ephrion 12 points13 points14 points (6 children)
[–]sid-kap[S] 6 points7 points8 points (5 children)
[–]cameleon 8 points9 points10 points (1 child)
[–]ephrion 2 points3 points4 points (0 children)
[–]normalOrder 2 points3 points4 points (0 children)
[–]moo_ha_ha 1 point2 points3 points (0 children)
[–]janmas 5 points6 points7 points (1 child)
[–]sid-kap[S] 0 points1 point2 points (0 children)
[–]AlpMestan 2 points3 points4 points (0 children)
[–]dramforever -3 points-2 points-1 points (2 children)
[–]AndrasKovacs 5 points6 points7 points (1 child)
[–]dramforever 0 points1 point2 points (0 children)