I was wondering, how can we do multiple things in a Haskell function?
For example, I have this code:
number = 0
increment :: Int -> Int
increment i = i 1
function :: String -> String
function s = s " world" AND increment number
I was wondering, how can we do something like this? I'm searching everywhere but I don't find a solution for this simple example :O
number
0
:function "hello"
"hello world" (AND the number = 1 now)
number
1
note: I know that AND
is not a syntax in Haskell but I wanted to make you understand what I wanted to say :)
CodePudding user response:
You can't modify variables in Haskell (they are not, in fact, variable). What you can do is return new values:
f (string, number) = (string " world", number 1)
which would be used like this:
Prelude> f ("hello", 0)
("hello world",1)
If you called this function with a variable instead of a literal, it would not change the value of that variable, because Haskell is designed to prevent that from happening:
Prelude> let n = 0
Prelude> f ("hello", n)
("hello world",1)
Prelude> print n
0
CodePudding user response:
the problem is: in haskell you don't have "mutable states" like in other programming languages: so "number = 1" wouldn't work in terms of "setting a State"
you could combine them as a result:
increment :: Int -> Int
increment i = i 1
stringCombine :: String -> String
stringcombine str = str "world"
combine i str = (increment i, stringCombine str)
or if you have a function with a side effect (like print, putStrLn) you have to use the IO Monad:
doSideEffects :: Int -> String -> IO Int
doSideEffects i str = do
putStrLn $ str "world"
return $ increment i