Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In haskell how can I reference code as a function

Tags:

haskell

I currently have an application which has a menu which will execute the following functions: add, remove and view. What I would like to know is how can I reference code as a function.

The code I am trying to reference is like this:

putStrLn "Please enter the username:"
addName <- getLine
appendFile "UserList.txt" ("\n" ++ addName)

Would I have to use a let function? For example:

let addUserName = 
putStrLn "Please enter the username:"
addName <- getLine
appendFile "UserList.txt" ("\n" ++ addName).
like image 388
MaGiCo UK Avatar asked Feb 17 '23 22:02

MaGiCo UK


1 Answers

First of all, you use the let keyword when you're in GHCi because you're in the IO monad. You normally wouldn't need it to define a function in source code. For example, you could have a file called "MyProgram.hs" containing:

addUserName = do
  putStrLn "Please enter the username:"
  addName <- getLine
  appendFile "UserList.txt" ("\n" ++ addName)

Then in GHCi, you type:

ghci> :l MyProgram.hs
ghci> addUserName

(That's :l for :load, not the numeral one.) Actually, you can define a function in GHCi, but it's a bit of a pain unless it's a one-liner. This would work:

ghci> let greet = putStrLn "Hello!"
ghci> greet
Hello!
like image 200
mhwombat Avatar answered Feb 22 '23 18:02

mhwombat