Haskell Quiz/Numeric Maze/Solution Ninju

From HaskellWiki
< Haskell Quiz‎ | Numeric Maze
Revision as of 22:12, 10 August 2008 by Ninju (talk | contribs) (Solution the Numeric Maze Quiz)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

I haven't yet any added any optimization, because I wanted to keep the program as simple (and therefore readable) as possible, but I might add some later.

As a Haskell beginner, comments on whether or not this is the right sort of way to go about a problem such as this are appreciated - I actually wrote another solution that took a different approach, but I think this is slightly better.

module Main where
import System.Environment
import Data.List

main :: IO ()
main = do args <- getArgs
          if length args == 2 
            then do let [a,b] = map read args
                    putStrLn $ show (solve a b)
            else putStrLn "Usage: solve START TARGET"
          return ()
    
data Operation = AddTwo Integer | Double Integer | Halve Integer

valid :: Operation -> Bool
valid (Halve x) = x `mod` 2 == 0
valid _         = True

apply :: Operation -> Integer
apply (AddTwo x) = x + 2 
apply (Double x) = x * 2 
apply (Halve x) = x `div` 2

solve :: Integer -> Integer -> [Integer]
solve a b = solve' [[a]] b
            where
            solve' paths target = case find ((== target) . last) paths of
                                    Just path -> path
                                    Nothing -> solve' (concatMap buildPathsFrom paths) target
            buildPathsFrom path = [ path ++ [apply (op (last path))] | op <- [AddTwo, Double, Halve], valid (op (last path)) ]