I agree with 200_success and am just typing out the full program because you said you were a beginner.
import Data.Strings
encode :: String -> String
encode = strReplace " A " " "
. strReplace "CHEESEBURGER" "CHEEZBURGER"
. strReplace "CAN I" "I CAN"
. strReplace "HAVE" "HAS"
. strToUpper
main :: IO ()
main = do
putStrLn "Enter your text to translate"
input <- getLine
putStrLn $ encode input
The main function would perhaps more commonly be written as:
main :: IO ()
main = do
putStrLn "Enter your text to translate"
putStrLn =<< encode <$> getLine
EDIT:
@MichaelKlein asked me to explain (<$>)
and (=<<)
, so I will do so as briefly as possible.
<$>
is the inline version of fmap
, which is the only function from the Functor
typeclass. A typeclass is somewhat like a interface in an imperial language like Java.
class Functor f where
fmap :: (a -> b) -> f a -> f b
fmap
is used to run a function (a -> b)
inside some data structure f a
fmap (+1) [1] == [2]
fmap (+1) (Just 3) == Just 4
(+1) <$> (Just 3) == Just 4
(<$>) :: f a -> ( a -> b ) -> f b
In Haskell, we treat the world as a datastructure IO
. So just in the same way that you can run a function inside a list or a maybe (like Just 3
), you can run a function inside a IO
.
encode :: String -> String
getLine :: IO String
encode <$> getLine :: IO String
(=<<)
is part of the Monad
typeclass, which is hard to explain briefly because you need to know about a few other typeclasses first.
(=<<) :: (a -> m b) -> m a -> m b
(=<<)
is pronounced "bind", and is a flipped version of the more common (>>=)
. The important bit is that Haskell has a special syntax for working with monads: the do
notation.
This:
main = do
input <- getLine
putStrLn input
Is syntatic sugar for this:
main = getLine >>= \input -> putStrLn input
Which is the same as this:
main = getLine >>= putStrLn
All of these are also equal:
main = do
putStrLn "burger"
input <- getLine
putStrLn $ encode input
main = putStrLn "burger"
>> getLine >>= \input -> putStrLn $ encode input
main = putStrLn "burger"
>> encode <$> getLine >>= putStrLn
main = do
putStrLn "burger"
putStrLn =<< encode <$> getLine
getLine
was to keep the Windows console open after the output was printed. Any other ideas on how to do that? – Michael Brandon Morris yesterdayforever
from Control.Monad – BlackCap yesterday