Reputation: 33
Like it says in the title: What does The last statement in a 'do' construct must be an expression mean? I know there are other subjects similar to mine, but I still can't find my error.
Code:
import System.Environment
check_args argc args i = do
putStrLn $ show (args !! i)
i <- return (i + 1)
if argc > i
then mydisplay2 argc args i
else return i
loop_args argc args = do
let i = 0
i <- check_args argc args i
main = do
args <- getArgs
putStrLn "The arguments are:"
loop_args (length args) args
Upvotes: 2
Views: 941
Reputation: 476493
The problem is located in the loop_args
function:
loop_args argc args = do
let i = 0
i <- check_args argc args i
It makes no sense to write i <- …
, since you here define a new variable named i
(that has not much to do with the i
in let i = 0
), and you do not use that variable at all. You can replace it with check_args argc args i
and the error will go away, but likely it will still not work the way you want this to work.
But in general, the program looks imperative, whereas Haskell is a declarative language. It means that every variable (so i
) is immutable, you thus can not loop by incrementing a variable. Furthermore in a declarative language, there is not much "looping", etc. The aim is not to specify how you want to do something, but what you want to do.
You likely here want to use a mapM_ :: (Foldable f, Monad m) => (a -> m b) -> f a -> m ()
that can move through a Foldable
object, and apply the monadic function on all items:
main = do
args <- getArgs
putStrLn "The arguments are:"
mapM_ putStrLn args
Upvotes: 4