Haskell mutliline guard inside do not working - haskell

Hello I am new to Haskell and I think that my problem is simple but important for me.
This works:
module Main where
main :: IO ()
main = do
inp <- getLine
let output i | odd i = "Alice" | even i = "Bob" | otherwise = "Weird"
putStrLn (output (read inp))
This does not work
module Main where
main :: IO ()
main = do
inp <- getLine
let output i
| odd i = "Alice"
| even i = "Bob"
| otherwise = "Weird"
putStrLn (output (read inp))
What I know:
Inside do you write "lets" or "let" before every function you declare and you do not write "in". Also when I wrote output as a non local function it worked.
What have I missunderstood?
edit:
would you recommend writing like this?
module Main where
main :: IO ()
main = do
inp <- getLine
let
output i
| odd i = "Alice"
| even i = "Bob"
putStrLn (output (read inp))

You need to indent the guards (with at least one extra space compared to the position of output), for example:
main :: IO ()
main = do
inp <- getLine
let output i
| odd i = "Alice"
| even i = "Bob"
| otherwise = "Weird"
putStrLn (output (read inp))
Since a number is either odd or even, you can just use otherwise for the even case:
main :: IO ()
main = do
inp <- getLine
let output i
| odd i = "Alice"
| otherwise = "Bob"
putStrLn (output (read inp))

Related

How does Haskell "desugar" getline in this do block?

I've read a few books on Haskell but haven't coded in it all that much, and I'm a little confused as to what Haskell is doing in a certain case. Let's say I'm using getLine so the user can push a key to continue, but I don't really want to interpret that person's input in any meaningful way. I believe this is a valid way of doing this:
main = do
_ <- getLine
putStrLn "foo"
I understand the basic gist of what's this is doing. getLine returns an IO String, and putStrLn takes a String and returns IO (), so if I theoretically wanted to print what the user typed into the console, I'd basically utilize the >>= operator from the Monad class. In my case, I believe my code is equivalent to getLine >> putStrLn "foo" since I'm discarding the return value of getLine.
However, what if I do this instead?
main = do
let _ = getLine
putStrLn "foo"
In this case, we're setting up a sort of lambda to work with something that will take an IO String, right? I could write a printIOString function to print the user's input and that would work fine. When I'm not actually using that IO String, though, the program behaves strangely... getLine doesn't even prompt me for input; the program just prints out "foo".
I'm not really sure what the "desugared" syntax would be here, or if that would shed some light on what Haskell is doing under the hood.
Let's warm up with a few more complicated examples.
main = do
x
x
x
putStrLn "foo"
where
x = do
getLine
What do you expect this to do? I don't know about you, but what I expect is for the program to get three lines and then print something. If we desugar the second do block, we get
main = do
x
x
x
putStrLn "foo"
where x = getLine
Since this is the desugaring of the other one, it behaves the same, getting three lines before printing. There's another line of thought that arrives at the same answer, if you don't find this first one intuitive. "Referential transparency", one of the defining features of Haskell, means exactly that you can replace a "reference" to something (that is, a variable name) with its definition, so the previous program should be exactly the same program as
main = do
getLine
getLine
getLine
putStrLn "foo"
if we are taking the equation x = getLine seriously. Okay, so we have a program that reads three lines and prints. What about this one?
main = do
x
x
putStrLn "foo"
where x = getLine
Get two lines and print. And this one?
main = do
x
putStrLn "foo"
where x = getLine
Get one line and then print. Hopefully you see where this is going...
main = do
putStrLn "foo"
where x = getLine
Get zero lines and then print, i.e. just print immediately! I used where instead of let to make the opening example a bit more obvious, but you can pretty much always replace a where block with its let cousin without changing its meaning:
main = let x = getLine in do
putStrLn "foo"
Since we don't refer to x, we don't even need to name it:
main = let _ = getLine in do
putStrLn "foo"
and this is the desugaring of the code you wrote.
The first case is desugared like you expected:
main = getLine >>= \_ -> putStrLn "foo"
which is equivalent to
main = getLine >> putStrLn "foo"
In the second case,
main = do
let _ = getLine
putStrLn "foo"
is desugared as
main = let _ = getLine in putStrLn "foo"
Since the _ = getLine value is not needed to evaluate the RHS of the let expression, the compiler is free to ignore it and the IO effect is never executed, which is why you're not prompted for CLI input anymore.
Even though both cases ignored the result of getLine the difference is that the first case evaluates getLine in an IO context while the second case evaluates getLine as a pure value. In IO the side-effects must executed and sequenced together, but in a pure context the compiler is free to ignore unused values.
I wouldn't recommend doing this as it's not very idiomatic, but you could write something like
printIOString :: IO String -> IO ()
printIOString ios = ios >>= putStrLn
and use it like printIOString getLine
According to https://stackoverflow.com/tags/do-notation/info,
do { let { _ = getLine } ; putStrLn "foo" }
=
do { let { _ = getLine } in putStrLn "foo" }
=
let { _ = getLine } in putStrLn "foo"
which by Haskell semantics is equivalent to
getLine & (\ _ -> putStrLn "foo")
=
putStrLn "foo"
(with x & f = f x), whereas indeed
do { _ <- getLine ; putStrLn "foo" }
=
getLine >>= (\ _ -> putStrLn "foo")
which can't be further simplified.

haskell parse error on input `=' Perhaps you need a 'let' in a 'do' block? e.g. 'let x = 5' instead of 'x = 5'

Can't get my haskell program to work
sort [] = []
sort (x:xs) = sort [a | a <- xs , a<=x ] ++ [x] ++ sort [a | a <- xs , a > x]
getList:: Int->[IO Int]
getList 0 = [] --declaring the empty list
getList n = [a | a <- [getNumber] ] ++ getList (n-1)
getNumber::IO Int --get number function
getNumber = do
s <- getLine
return (read s)
--Main function to handle
main = do
p <- getNumber -- taking the number of variable
lst <- sequence (getList p) --calling gtlistFunction to input the list
print (sort lst) --print
Error:
quicksort.hs:13:6: error:
parse error on input `='
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
|
13 | main = do
| ^
You must indent all do-blocks:
-- NOT correct: this will fail
main = do
putStrLn "This is..."
putStrLn "WRONG!"
-- Correct:
main = do
putStrLn "This is..."
putStrLn "correct!"
The number of spaces doesn't matter as long it is consistent.
To avoid this you could use c-like notation:
-- Also correct:
main = do {
putStrLn "This is...";
putStrLn "also correct!";
}
And this leaves you free to indent as you like. Example:
-- Also correct:
main = do
{ putStrLn "This is..."
; putStrLn "also correct!"
;}
Without indentation, the parser doesn't know that main = ... starts a new definition, separate from the preceding definition of getNumber. The following would work fine:
getNumber::IO Int
getNumber = do
s <- getLine
return (read s)
main = do
p <- getNumber
lst <- sequence (getList p)
print (sort lst)
The transition from one-space indentation to no indentation is enough to tell the parser that return (read s) is the last line of the do block defining getNumber, and that main = do is the beginning of a new top-level definition.
Either indenting your code, or using the explicit brace syntax in AJFarmar's answer, lets the parser know where one definition ends and the next begins.

Let block gives indentation error

I know what an indentation error is, but I have no idea why I'm getting this error here, while every is aligned, trying to solve it for 2 hours.
Account.hs:40:25: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
40 | let amount = readLn :: IO Int
| ^
Failed, 0 modules loaded.
main = do
putStrLn $ "Press one to create a new account"
let g = getLine
enteredValue = read g :: Int
if g == 1
then do putStrLn $ "Enter your name "
let name = getLine
putStrLn $ "Enter the initial amount"
let amount = readLn :: IO Int
value = Account (name,1,amount) Saving
show value
else do putStrLn $ "Nothing"
I also tried this version but this also gives incorrect indentation or mismatched brackets:
main = do
putStrLn $ "Press one to create a new account"
let g = getLine
enteredValue = read g :: Int
if g == 1
then do putStrLn $ "Enter your name "
let name = getLine
putStrLn $ "Enter the initial amount"
amount = readLn :: IO Int
value = Account (name,1,amount) Saving
show value
else do putStrLn $ "Nothing"
The problem is here:
-- |<---- "column 0" of this 'do' block
then do putStrLn $ "Enter your name "
-- | still good; a 'let' statement:
let name = getLine
-- |<---- "column 0" of this 'let' block
putStrLn $ "Enter the initial amount"
-- | Huh, there's no '=' in ^this^ declaration?
let amount = readLn :: IO Int
-- ^^^ Why is there a 'let' within another let binding?
-- I still haven't seen a '='. Better throw a parse error.
Basically, putStrLn $ "Enter the initial amount" is aligned with name = ... in the preceding line, so the compiler reads it as a declaration (part of the same let block).
To fix your indentation errors, it should be:
main = do
putStrLn $ "Press one to create a new account"
let g = getLine
enteredValue = read g :: Int
if g == 1
then do putStrLn $ "Enter your name "
let name = getLine
putStrLn $ "Enter the initial amount"
let amount = readLn :: IO Int
value = Account (name,1,amount) Saving
show value
else do putStrLn $ "Nothing"
But then you'll run into type errors:
read g is wrong: read takes a String, but g :: IO String
g == 1 is wrong: 1 is an Int, but g :: IO String
show value is wrong: show returns a String, but you're using it as an IO action
You haven't shown the declaration of Account, but you're likely going to have issues with name and amount, too
You probably want something like:
main = do
putStrLn $ "Press one to create a new account"
g <- getLine
let enteredValue = read g :: Int
if enteredValue == 1
then do putStrLn $ "Enter your name "
name <- getLine
putStrLn $ "Enter the initial amount"
amount <- readLn :: IO Int
let value = Account (name,1,amount) Saving
putStrLn (show value)
else do putStrLn $ "Nothing"
Basically, use v <- expr to go from expr :: IO Something to v :: Something.
Other notes:
g <- getLine; let enteredValue = read g :: Int better written as enteredValue <- readLn :: IO Int
putStrLn (show value) can be shortened to print value
you don't need do for a single expression (nor $ for a single operand): ... else putStrLn "Nothing"
There is more wrong to your code than just the Indentation Errors - so my first suggestion would be reading a bit of learn you a haskell for great good.
Next there are two assignment operators in haskell - one binds the result of an action … <- … and the other one is a local definition/declaration of a pure computation let … = ….
Moreover you can improve your reading a value by taking account of the possible false input, that someone could give you (intentionally and unintentionally) by replacing read with readMaybe, where the latter returns a Maybe something, for example readMaybe "1" = Just 1 :: Maybe Int or readMaybe "foo" = Nothing :: Maybe Int.
Regarding your indentation it is best that you compare one solution to your program with yours own:
import Text.Read (readMaybe)
data Type = Saving | Checking
deriving (Show)
data Account = Account (String,Int,Int) Type
deriving (Show)
main :: IO ()
main = do
putStrLn "Press one to create a new account"
g <- getLine
let enteredValue = readMaybe g :: Maybe Int
here the result of getLine and entered value have the same scope so they have the same indentation - we only change the scope after the next if where the then-block - and the else-block do not share the 'declarations' of each branch, so you couldn't use name in the else-block, but enteredValue can be used in both.
if enteredValue == Just 1
then do putStrLn "Enter your name "
name <- getLine
putStrLn "Enter the initial amount"
amount' <- fmap readMaybe getLine
here again name and amount' share the same scope, and pattern matching on amount' creates a new scope where amount is visible and the match on Nothing where you cannot use this variable.
case amount' of
Just amount -> print $ Account (name,1,amount) Saving
Nothing -> putStrLn "Nothing"
else putStrLn "Nothing"
let is for binding values, which is done in the form let x = y+z, where x is the name (aka "identifier") being bound, and y+z is the expression to which it is being bound.
In your example, I see three bindings: name, amount, and value. The rest are not value bindings, but actions.
In the do notation, actions do not need a let. You just write them one after another. So:
let name = getLine
putStrLn $ "Enter the initial amount"
let amount = readLn :: IO Int
let value = Account (name,1,amount) Saving
show value
But wait! This is not all!
getLine is not actually an expression of type String, as you seem to be hoping here. Rather, getLine is an action. In order to get it to "run" and "produce" a String value, you need to use the <- construct instead of let:
name <- getLine
Similarly with readLn:
amount <- readLn :: IO Int
Finally, show value is not actually an action that would print the value to the screen. show is a function that takes a value and return a String. It doesn't "do" anything (i.e. doesn't produce any outside effects), so you can't use it in place of an action in the do notation. If you wanted an action that would print a value to the screen, that would be print:
print value
Gathering everything together:
name <- getLine
putStrLn $ "Enter the initial amount"
amount <- readLn :: IO Int
let value = Account (name,1,amount) Saving
print value
And after fixing all of that, you'll have similar difficulties with the first part of your program, where you have let g = getLine instead of g <- getLine.

Correct way of reading from stdin in haskell

I have a program that depending on the arguments given works in different ways:
If there are 2 arguments - it takes 2nd argument as a filename, reads from it and then simply prints it out.
If there is 1 argument - it reads from stdin and also prints it out.
Here is the code:
main :: IO ()
main = do
-- Read given arguments
args <- getArgs
-- If file containing gramma was given
if length args == 2 then do
hfile <- openFile (last args) ReadMode
content <- hGetContents hfile
let inGramma = getGramma content
doJob (head args) inGramma
hClose hfile
return ()
-- If no file was given - reads from stdin
else if length args == 1 then do
content <- getContents
let inGramma = getGramma content
doJob (head args) inGramma
return ()
else do putStrLn "Invalid count of arguments!"
The problem is, when it reads from stdin, after every new line (enter pressed), it prints that line and than reads next. I need it to wait for the whole input and than print it out (after Ctrl+D).
Here are the functions used in that code:
-- | Structure of gramma
data GrammaStruct = Gramma
{ nonTerminals :: NonTerminals
, terminals :: Terminals
, start :: Start
, rules :: Rules
} deriving (Eq)
-- | Representation of gramma
instance Show GrammaStruct where
show (Gramma n t s r) =
init (showSplit n) ++
"\n" ++ init (showSplit t) ++
"\n" ++ showStart s ++
"\n" ++ init (showRules r)
-- | Print gramma
showGramma :: GrammaStruct -> IO ()
showGramma gr = do
putStrLn $ show gr
-- | Transforms string given from file of stdin into gramma representation in app
getGramma :: String -> GrammaStruct
getGramma hIn = procLns (lines hIn)
-- | Depending on option given, provides required functionality
doJob :: String -> GrammaStruct -> IO ()
doJob op gramma
| op == "-i" = showGramma gramma
Thank you.
The problem here is that getContents uses lazy IO, making the input stream to be processed line-by-line. If you want to force it to read the whole input before starting performing the job you can use the following hack:
...
if length args == 1 then do
content <- getContents
length content `seq` return () -- force the input to be fully read now
let inGramma = getGramma content
doJob (head args) inGramma
return ()
Alternatively, use evaluate, or look in Hackage for a strict IO module providing a strict getContents. For instance, I just found the strict-io package providing System.IO.Strict.getContents. Using that you should be able to write (untested)
import qualified System.IO.Strict as S
...
if length args == 1 then do
content <- run S.getContents
...
That's not answering the question but instead of testing the length of the arguments, you can pattern match against it and return the correct content
main = do
let (opt, contentM) = case getArgs of
[opt] -> (op, getContent)
[opt, file] -> (op, hGetContent file)
_ -> error ("Invalid count of argument")
inGramma <- fmap getGramma contentM
doJob opt inGramma

Scope of input haskell

I'm having trouble taking in an input. Running it through functions. And outputting it. I have tried to do this in 2 different ways but neither work. Looking around online I see everyone only using the variable of the input inside the main. This would explain why I'm getting a "not in scope" error. But how would this be possible? Here are my two attempts.
result = lcm 3 inp
main = do
inp <- getLine
putStr result
and this:
main = do
inp <- getLine
putStr result
where
result = lcm 3 inp
inp exists only within the scope of the do expression, which explains why you get an error in the first version.
As for the second version. it can be rewritten to:
main = e
where
e = do
inp <- getLine
putStr result
result = lcm 3 inp
The two where bindings have different scopes, which is why a local binding from one expression is inaccessible from the other.
This, on the other hand, should work:
main = do
inp <- getLine
let result = lcm 3 inp
putStr result
result is now defined within the do notation scope, so it can use inp. If you still want to use the where clause, result will need to accept inp as an argument:
main = do
inp <- getLine
putStr result
where
result inp = lcm 3 inp
Let's see the types of the things you use:
*Main> :t lcm
lcm :: Integral a => a -> a -> a
*Main> let result inp = lcm 3 inp
*Main> :t result
result :: Integral a => a -> a
But you read in a String:
*Main> :t getLine
getLine :: IO String
So, you need to convert a String to something like an integer, and convert an Inegral the result returned back to Striing for printing.
main = do
inp <- getLine
putStr $ show $ result (read inp)

Resources