2
\$\begingroup\$

Here is part of my build system.

guessCompilers :: Options -> IO Options
guessCompilers options =  foldl (>>=) (return options) modifiers where 
  modifiers = 
    [guessMetapost 
     -- guessAsymptote, 
     -- guessTex, 
     -- guessLatex, 
     -- guessXelatex
    ]   
guessMetapost :: Options -> IO Options
guessMetapost opts = if isJust $ optMetaPost opts 
                         then 
                           putStrLn $ printf "using enforced Metapost compiler: %s" (fromJust $optMetaPost opts)
                           >> return opts
                         else do 
                           cc <- compiler Metapost.interface
                           if isJust cc then putStrLn $ printf "found Metapost compiler: %s" (fromJust cc)
                                             else putStrLn "found Metapost compiler: none"

Compiler can be spectified by cmd args or can be guessed. But double checking for Nothing is not cool in my opinion. Also, I heard fromJust is evil. Any suggestions to improve my code?

\$\endgroup\$
3
\$\begingroup\$

Pattern match instead of using isJust and fromJust. (You could use maybe instead of pattern matching, but I think pattern matching is clearer in this case.)

This eliminates the possibility of forgetting to ensure a value is a Just before calling fromJust on it.

guessMetapost :: Options -> IO ()
guessMetapost opts
   = case optMetaPost opts of
         Just mcc -> putStrLn $ printf "using enforced Metapost compiler: %s" mcc
         Nothing -> do
           cc' <- compiler Metapost.interface
           case cc' of
               Just cc -> putStrLn $ printf "found Metapost compiler: %s" cc
               Nothing -> putStrLn "found Metapost compiler: none"

(Your code wasn't consistently returning any options, so I've stripped that bit out.)

\$\endgroup\$
  • 2
    \$\begingroup\$ You can also get rid of putStrLn $ printf ..., and simply write printf. There is an IO a instance of PrintfType. \$\endgroup\$ – danr Jul 30 '12 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.