Scorporo un pezzo di codice, semplificandolo anche, da una programma inteso per terminale.
- Codice:
-- hask.hs
{-
if you want to try that code by yourself,
you may need to 'cabal install extra' first
-}
import Data.List.Extra (trim)
-- force the user to type something!
main :: IO ()
main = insertSomething >>= putStrLn . (">>> you\'ve typed: " ++)
insertSomething :: IO String
insertSomething = do putStr ">>> insert something: "
h . trim =<< getLine
where h :: String -> IO String
h xs = if null xs then insertSomething else return xs
- Codice:
$ runghc hask.hs
>>> insert something: something
>>> you've typed: something
Ok, interpretato fa quel che mi aspetto. Lo compilo (con successo)
- Codice:
$ ghc hask.hs
e lo provo
- Codice:
$ ./hask
niente, un rettangolino sta aspettando che io faccia qualcosa. Nel dubbio batto qualcosa
- Codice:
$ ./hask
something
>>> insert something: >>> you've typed: something
Che succede? Doveva chiedermi insert something:, invece no. Ha aspettato che io inserissi qualcosa, per poi farne la richiesta.
Allora provo ad usare putStrLn al posto di putStr in insertSomething (perché non farlo?):
- Codice:
-- hask.hs
import Data.List.Extra (trim)
-- force the user to type something!
main :: IO ()
main = insertSomething >>= putStrLn . (">>> you\'ve typed: " ++)
insertSomething :: IO String
insertSomething = do putStrLn ">>> insert something: "
h . trim =<< getLine
where h :: String -> IO String
h xs = if null xs then insertSomething else return xs
Intepretato fa quel che mi aspetto (va a capo ogni volta, ma fa niente) e , sorpresa!, anche da compilato:
- Codice:
$ ./hask
>>> insert something:
ciao
>>> you've typed: ciao
Va bene, cosa non va in putStr? O meglio: mi sfugge qualcosa?