Haskell – Hello World with VS Code



In the previous section we installed GHCI and used it in the Command Prompt. In this section we will use Visual Studio Code as the IDE to be able to write and manage code easier.

VS Code

First we download and install VS Code at https://code.visualstudio.com/.

Install Extension on VS Code

We install the following extensions:

  • Haskell Syntax Highlighting: Display the text color of keywords, comments, variables … etc
  • haskell-linter: check the syntax and suggest spelling clean code

We only need 2 extensions that are enough, not too much.

Set hlint

At now, haskell-linter Just a wrapper of the hlint software, which means that this extension will actually use the hlint to perform the work of a software. linter. So after installing, this extension will report an error not found hlint.

So we have to install hlint first, we can install it through Cabal – this is a set of tools to help manage software packages for Haskell, which comes when we install Haskell Platform.

First we run the command cabal update:

C:>cabal update
Downloading the latest package list from package.haskell.org

Next we install hlint by command cabal install hlint:

C:>cabal install hlint
Resolving dependencies...

Cabal will load and install the hlint, which can take about 5-10 minutes.

Once installed, we can test it out by running the command hlint -V to see the current hlint version:

C:>hlint -V
HLint v3.1.1, Copyright Neil Mitchell 2006-2020

Project creation

We create a certain directory, then open that folder in VS Code, then create a file, named such as main.hs, *.hs is the extension of the Haskell file. Write the following code in this file:

main :: IO()
main = putStrLn "Hello World"

To run, we open up Terminal in VS Code, compile with the command ghc main.hs:

The editor will compile and link the file main.hs and create file main.exe. To run, we just call this file:

Alternatively we can also use commands runhaskell main.hs, This command will do the interpreter job, that is, do not compile the .exe file, but only run each command like the languages ​​Python, Perl, Ruby … etc


When we write a piece of Haskell code the compiler will always look for a variable named main and the type is IO(). Also, the rule of Haskell is that when declaring a variable, it must assign data to that variable. Here the line main :: IO() is the line that declares the type, and the line main = putStrLn "Hello World" followed by the assignment line, if there is no first and second line then the compiler will always report an error.

We are here for an example so we print the line to the screen. Actually we could write the following:

main :: IO()
main = return() --- Do nothing

Hope this helps!

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *