Haskell Language


This draft deletes the entire topic.

expand all collapse all

Examples

  • 6

    Online REPL

    The easiest way to get started writing Haskell is probably by going to the Haskell website or Try Haskell and use the online REPL (read-eval-play-loop) on the home page. The online REPL supports most basic functionality and even some IO. There is also a basic tutorial available which can be started by typing the command help. An ideal tool to start learning the basics of Haskell and try out some stuff.

    GHC(i)

    For programmers that are ready to engage a little bit more, there is GHCi, an interactive environment that comes with the Glorious/Glasgow Haskell Compiler. The GHC can be installed separately, but that is only a compiler. In order to be able to install new libraries, tools like Cabal and Stack must be installed as well. It is probably easier to install a Haskell Platform. The platform exists in two flavours:

    1. The minimal distribution contains only GHC (to compile) and Cabal/Stack (to install and build packages)
    2. The full distribution additionally contains tools for project development, profiling and coverage analysis. Also an additional set of widely-used packages is included.

    These platforms can be installed by downloading an installer and following the instructions or by using your distribution's package manager (note that this version is not guaranteed to be up-to-date):

    • Ubuntu, Debian, Mint:

      sudo apt-get install haskell-platform
      
    • Fedora:

      sudo dnf install haskell-platform
      
    • Redhat:

      sudo yum install haskell-platform
      
    • Gentoo:

      sudo layman -a haskell
      sudo emerge haskell-platform
      
    • OSX with Homebrew:

      brew cask install haskell-platform
      
    • OSX with MacPorts:

      sudo port install haskell-platform
      

    Once installed, it should be possible to start GHCi by invoking the ghci command anywhere in the terminal. If the installation went well, the console should look something like

    me@notebook:~$ ghci
    GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
    Prelude> 
    

    possibly with some more information on what libraries have been loaded before the Prelude>. Now, the console has become a Haskell REPL and you can execute Haskell code as with the online REPL. In order to quit this interactive environment, one can type :qor :quit. For more information on what commands are available in GHCi, type :? as indicated in the starting screen.

    Because writing the same things again and again on a single line is not always that practically, it might be a good idea to write the Haskell code in files. These files normally have .hs for an extension and can be loaded into the REPL by using :l or :load.

    As mentioned earlier, GHCi is a part of the GHC, which is actually a compiler. This compiler can be used to transform a .hs file with Haskell code into a running program. Because a .hs file can contain a lot of functions, a main function must be defined in the file. This will be the starting point for the program. The file test.hs can be compiled with the command

    ghc test.hs
    

    this will create object files and an executable if there were no errors and the main function was defined correctly.

    More advanced tools

    1. It has already been mentioned earlier as package manager, but stack can be a useful tool for Haskell development in completely different ways. Once installed, it is capable of

      • installing (multiple versions of) GHC
      • project creation and scaffolding
      • dependency management
      • building and testing projects
      • benchmarking
    2. IHaskell is a haskell kernel for IPython and allows to combine (runnable) code with markdown and mathematical notation. For OS X users, there is even an application called Kronos Haskell

  • 45

    A basic "Hello, World!" program in Haskell can be expressed concisely in just two lines:

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

    The first line is an optional type annotation, indicating that main is an I/O action of type IO (). This means main yields something of type () (the empty tuple, containing no information)

    Put this into a helloworld.hs file and compile it using a Haskell compiler, such as GHC:

    ghc -o helloworld helloworld.hs
    

    Use runhaskell or runghc to run the program in interpreted mode:

    runhaskell helloworld.hs
    

    The interactive REPL can also be used instead of compiling. It comes shipped with most Haskell environments, such as ghci:

    ghci> putStrLn "Hello World!"
    

    Alternatively, load scripts into ghci from a file using load (or :l). This saves all scripts for future review:

    ghci> :load helloworld
    

    :reload (or :r) reloads everything in ghci:

    Prelude> :load helloworld.hs 
    [1 of 1] Compiling Main             ( helloworld.hs, interpreted )
    
    <some time later after some edits>
    
    *Main> :r
    Ok, modules loaded: Main.
    

    Explanation:

    This first line is a type signature, declaring the type of main:

    main :: IO ()
    

    IO () type objects often describe actions which write to the outside world.

    Because Haskell has a fully-fledged Hindley-Milner type system, type signatures are technically optional: if you simply omit the main :: IO (), the compiler will be able to infer this information itself by looking at the definition of main. However, it is very much considered bad style not to write type signatures for top-level definitions. The reasons include:

    • Type signatures in Haskell are a very helpful piece of documentation because the type system is so expressive that you often can see what sort of thing a function is good for simply by looking at its type. This “documentation” can be conveniently accessed with tools like GHCi. And unlike normal documentation, the compiler's type checker will make sure it actually matches the function definition!
    • Type signatures keep bugs local. If you make a mistake in the definition of main, the compiler may not immediately report an error, but instead simply infer a nonsensical type for main, with which it actually typechecks. You may then get a cryptic error message when using it.
      With a signature, the compiler is very good at spotting bugs right where they happen.

    This second line does the actual work:

    main = putStrLn "Hello, World!"
    

    If you come from an imperative language, it may be helpful to note that the definition can also be written as:

    main = do {
       putStrLn "Hello, World!";
       return ()
    }
    

    Or preferably (Haskell has layout-based scoping):

    main = do
        putStrLn "Hello, World!"
        return ()
    

    In actuality, the do syntax is just syntactic sugar for sequencing monads like IO, and return () is a no-op action. It is completely equivalent to just defining main = putStrLn "Hello, World!". The “statement” putStrLn "Hello, World!" can be seen as a complete program, and you simply define main to refer to this program.

    To see why, you can look up the signature of putStrLn:

    putStrLn :: String -> IO ()
    

    This is a function that takes a string as its argument and outputs an IO-action (i.e. a program that the runtime can execute). What the runtime will actually execute is always the main action, so we simply need to define it as equal to putStrLn "Hello, World!".

  • 19

    The factorial function is a Haskell "Hello World!" (and for functional programming generally) in the sense that it succinctly demonstrates basic principles of the language.

    Variation 1

    fac :: (Integral a) => a -> a
    fac n = product [1..n]
    

    Live demo

    • Integral is the class of integral number types. Examples include Int and Integer.
    • (Integral a) => places a constraint on the type a to be in said class
    • fac :: a -> a says that fac is a function that takes an a and returns an a
    • product is a function that accumulates all numbers in a list by multiplying them together.
    • [1..n] is special notation which desugars to enumFromTo 1 n, and is the range of numbers 1 ≤ x ≤ n.

    Variation 2

    fac :: (Integral a) => a -> a
    fac 0 = 1
    fac n = n * fac (n - 1)
    

    Live demo

    This variation uses pattern matching to split the function definition into separate cases. The first definition is invoked if the argument is 0 (sometimes called the stop condition) and the second definition otherwise (the order of definitions is significant). It also exemplifies recursion as fac refers to itself.


    It is worth noting that, due to rewrite rules, both versions of fac will compile to identical machine code when using GHC with optimizations activated. So, in terms of efficiency, the two would be equivalent.

Please consider making a request to improve this example.

Remarks

Haskell logo

Haskell is an advanced purely-functional programming language.

Features:

  • Statically typed: Every expression in Haskell has a type which is determined at compile time. Static type checking is the process of verifying the type safety of a program based on analysis of a program's text (source code). If a program passes a static type checker, then the program is guaranteed to satisfy some set of type safety properties for all possible inputs.
  • Purely functional: Every function in Haskell is a function in the mathematical sense. There are no statements or instructions, only expressions which cannot mutate variables (local or global) nor access state like time or random numbers.
  • Concurrent: Its flagship compiler, GHC, comes with a high-performance parallel garbage collector and light-weight concurrency library containing a number of useful concurrency primitives and abstractions.
  • Lazy evaluation: Functions don't evaluate their arguments. Delays the evaluation of an expression until its value is needed.
  • General-purpose: Haskell is built to be used in all contexts and environments.
  • Packages: Open source contribution to Haskell is very active with a wide range of packages available on the public package servers.

The latest standard of Haskell is Haskell 2010. As of May 2016, a group is working on the next version, Haskell 2020.

The official Haskell documentation is also a comprehensive and useful resource. Great place to find books, courses, tutorials, manuals, guides, etc.

Versions

VersionRelease Date
Haskell 20102012-07-10
Haskell 982002-12-01
Still have a question about Getting started with Haskell Language? Ask Question

Topic Outline