Haskell Assignment

All the examples in this chapter can be saved into a Haskell source file and then evaluated by loading that file into GHC. Do not include the "Prelude>" prompts part of any example. When that prompt is shown, it means you can type the following code into an environment like GHCi. Otherwise, you should put the code in a file and run it.


In the last chapter, we used GHCi as a calculator. Of course, that's only practical for short calculations. For longer calculations and for writing Haskell programs, we want to keep track of intermediate results.

We can store intermediate results by assigning them names. These names are called variables. When a program runs, each variable is substituted for the value to which it refers. For instance, consider the following calculation

Prelude> 3.141592653 * 5^2 78.539816325

That is the approximate area of a circle with radius , according to the formula . Of course, it is cumbersome to type in the digits of , or even to remember more than the first few. Programming helps us avoid mindless repetition and rote memorization by delegating these tasks to a machine. That way, our minds stay free to deal with more interesting ideas. For the present case, Haskell already includes a variable named that stores over a dozen digits of for us. This allows for not just clearer code, but also greater precision.

Prelude> pi 3.141592653589793 Prelude> pi * 5^2 78.53981633974483

Note that the variable and its value, , can be used interchangeably in calculations.

Haskell source files[edit]

Beyond momentary operations in GHCi, you will save your code in Haskell source files (basically plain text) with the extension . Work with these files using a text editor appropriate for coding (see the Wikipedia article on text editors). Proper source code editors will provide syntax highlighting, which colors the code in relevant ways to make reading and understanding easier. Vim and Emacs are popular choices among Haskell programmers.

To keep things tidy, create a directory (i.e. a folder) in your computer to save the Haskell files you will create while doing the exercises in this book. Call the directory something like . Then, create a new file in that directory called with the following code:

That code defines the variable as the value .

Note: make sure that there are no spaces at the beginning of the line because Haskell is sensitive to whitespace.

Next, with your terminal at the directory, start GHCi and load the file using the command:

Prelude> :load Varfun.hs [1 of 1] Compiling Main ( Varfun.hs, interpreted ) Ok, modules loaded: Main.

Note that can be abbreviated as (as in ).

If GHCi gives an error like , you probably running GHCi in the wrong directory or saved your file in the wrong directory. You can use the command to change directories within GHCi (for instance, ).

With the file loaded, GHCi's prompt changes from "Prelude" to "*Main". You can now use the newly defined variable in your calculations.

*Main> r 5.0 *Main> pi * r^2 78.53981633974483

So, we calculated the area of a circle with radius of 5.0 using the well-known formula . This worked because we defined in our Varfun.hs file and comes from the standard Haskell libraries.

Next, we'll make the area formula easier to quickly access by defining a variable name for it. Change the contents of the source file to:


Save the file. Then, assuming you kept GHCi running with the file still loaded, type (or abbreviate version ).

*Main> :reload Compiling Main ( Varfun.hs, interpreted ) Ok, modules loaded: Main. *Main>

Now we have two variables and .

*Main> area 78.53981633974483 *Main> area / r 15.707963267948966


Note: The keyword (a word with a special meaning) lets us define variables directly at the GHCi prompt without a source file. This looks like:

Prelude> let area = pi * 5 ^ 2

Although sometimes convenient, assigning variables entirely in GHCi this way is impractical for any complex tasks. We will usually want to use saved source files.


Besides the working code itself, source files may contain text comments. In Haskell there are two types of comment. The first starts with and continues until the end of the line:

x=5-- x is 5.y=6-- y is 6.-- z = 7 -- z is not defined.

In this case, and are defined in actual Haskell code, but is not.

The second type of comment is denoted by an enclosing and can span multiple lines:

answer=2*{- block comment, crossing lines and... -}3{- inline comment. -}*7

We use comments for explaining parts of a program or making other notes in context. Beware of comment overuse as too many comments can make programs harder to read. Also, we must carefully update comments whenever we change the corresponding code. Outdated comments can cause significant confusion.

Variables in imperative languages[edit]

Readers familiar with imperative programming will notice that variables in Haskell seem quite different from variables in languages like C. If you have no programming experience, you could skip this section, but it will help you understand the general situation when encountering the many cases (most Haskell textbooks, for example) where people discuss Haskell in reference to other programming languages.

Imperative programming treats variables as changeable locations in a computer's memory. That approach connects to the basic operating principles of computers. Imperative programs explicitly tell the computer what to do. Higher-level imperative languages are quite removed from direct computer assembly code instructions, but they retain the same step-by-step way of thinking. In contrast, functional programming offers a way to think in higher-level mathematical terms, defining how variables relate to one another, leaving the compiler to translate these to the step-by-step instructions that the computer can process.

Let's look at an example. The following code does not work in Haskell:

An imperative programmer may read this as first setting and then changing it to . In Haskell, however, the compiler will respond to the code above with an error: "multiple declarations of ". Within a given scope, a variable in Haskell gets defined only once and cannot change.

The variables in Haskell seem almost invariable, but they work like variables in mathematics. In a math classroom, you never see a variable change its value within a single problem.

In precise terms, Haskell variables are immutable. They vary only based on the data we enter into a program. We can't define two ways in the same code, but we could change the value by changing the file. Let's update our code from above:


Of course, that works just fine. We can change in the one place where it is defined, and that will automatically update the value of all the rest of the code that uses the variable.

Real-world Haskell programs work by leaving some variables unspecified in the code. The values then get defined when the program gets data from an external file, a database, or user input. For now, however, we will stick to defining variables internally. We will cover interaction with external data in later chapters.

Here's one more example of a major difference from imperative languages:

Instead of "incrementing the variable " (i.e. updating the value in memory), this Haskell code is a recursive definition of (i.e. defining it in terms of itself). We will explain recursion in detail later on. For this specific case, if had been defined with any value beforehand, then in Haskell would bring an error message. is akin to saying, in a mathematical context, that , which is plainly wrong.

Because their values do not change within a program, variables can be defined in any order. For example, the following fragments of code do exactly the same thing:

In Haskell, there is no notion of " being declared before " or the other way around. Of course, using will still require a value for , but this is unimportant until you need a specific numeric value.


Changing our program every time we want to calculate the area of new circle is both tedious and limited to one circle at a time. We could calculate two circles by duplicating all the code using new variables and for the second circle:[1]


Of course, to eliminate this mindless repetition, we would prefer to have simply one function for area and then apply it to different radii.

A function takes an argument value (or parameter) and gives a result value (essentially the same as in mathematical functions). Defining functions in Haskell is like defining a variable, except that we take note of the function argument that we put on the left hand side. For instance, the following defines a function which depends on an argument named :

Look closely at the syntax: the function name comes first ( in our example), followed by a space and then the argument ( in the example). Following the sign, the function definition is a formula that uses the argument in context with other already defined terms.

Now, we can plug in different values for the argument in a call to the function. Save the code above in a file, load it into GHCi, and try the following:

*Main> area 5 78.53981633974483 *Main> area 3 28.274333882308138 *Main> area 17 907.9202768874502

Thus, we can call this function with different radii to calculate the area of any circle.

Our function here is defined mathematically as

In mathematics, the parameter is enclosed between parentheses, as in or . Haskell code will also work with parentheses, but we omit them as a convention. Haskell uses functions all the time, and whenever possible we want to minimize extra symbols.

We still use parentheses for grouping expressions (any code that gives a value) that must be evaluated together. Note how the following expressions are parsed differently:

5*3+2-- 15 + 2 = 17 (multiplication is done before addition)5*(3+2)-- 5 * 5 = 25 (thanks to the parentheses)area5*3-- (area 5) * 3area(5*3)-- area 15

Note that Haskell functions take precedence over all other operators such as and , in the same way that, for instance, multiplication is done before addition in mathematics.


What exactly happens when you enter an expression into GHCi? After you press the enter key, GHCi will evaluate the expression you have given. That means it will replace each function with its definition and calculate the results until a single value remains. For example, the evaluation of proceeds as follows:

area 5 => { replace the left-hand side area r = ... by the right-hand side ... = pi * r^2 } pi * 5 ^ 2 => { replace pi by its numerical value } 3.141592653589793 * 5 ^ 2 => { apply exponentiation (^) } 3.141592653589793 * 25 => { apply multiplication (*) } 78.53981633974483

As this shows, to apply or call a function means to replace the left-hand side of its definition by its right-hand side. When using GHCi, the results of a function call will then show on the screen.

Some more functions:

  • Explain how GHCi evaluates .
  • Define a function that subtracts 12 from half its argument.

Multiple parameters[edit]

Functions can also take more than one argument. For example, a function for calculating the area of a rectangle given its length and width:

*Main> areaRect 5 10 50

Another example that calculates the area of a triangle :

*Main> areaTriangle 3 9 13.5

As you can see, multiple arguments are separated by spaces. That's also why you sometimes have to use parentheses to group expressions. For instance, to quadruple a value , you can't write

quadruplex=doubledoublex-- error

That would apply a function named to the two arguments and . Note that functions can be arguments to other functions (you will see why later). To make this example work, we need to put parentheses around the argument:


Arguments are always passed in the order given. For example:

*Main> minus 10 5 5 *Main> minus 5 10 -5

Here, evaluates to , but evaluates to because the order changes.

  • Write a function to calculate the volume of a box.
  • Approximately how many stones are the famous pyramids at Giza made up of? Hint: you will need estimates for the volume of the pyramids and the volume of each block.

On combining functions[edit]

Of course, you can use functions that you have already defined to define new functions, just like you can use the predefined functions like addition or multiplication (operators are defined as functions in Haskell). For example, to calculate the area of a square, we can reuse our function that calculates the area of a rectangle:

*Main> areaSquare 5 25

After all, a square is just a rectangle with equal sides.

  • Write a function to calculate the volume of a cylinder. The volume of a cylinder is the area of the base, which is a circle (you already programmed this function in this chapter, so reuse it) multiplied by the height.

Local definitions[edit]


When defining a function, we sometimes want to define intermediate results that are local to the function. For instance, consider Heron's formula for calculating the area of a triangle with sides , , and :


The variable is half the perimeter of the triangle and it would be tedious to write it out four times in the argument of the square root function .

Simply writing the definitions in sequence does not work...

heronabc=sqrt(s*(s-a)*(s-b)*(s-c))s=(a+b+c)/2-- a, b, and c are not defined here

... because the variables , , are only available in the right-hand side of the function , but the definition of as written here is not part of the right-hand side of . To make it part of the right-hand side, we use the keyword.

Note that both the and the local definitions are indented by 4 spaces, to distinguish them from subsequent definitions. Here is another example that shows a mix of local and top-level definitions:

areaTriangleTrigabc=c*height/2-- use trigonometrywherecosa=(b^2+c^2-a^2)/(2*b*c)sina=sqrt(1-cosa^2)height=b*sinaareaTriangleHeronabc=result-- use Heron's formulawhereresult=sqrt(s*(s-a)*(s-b)*(s-c))s=(a+b+c)/2


If you look closely at the previous example, you'll notice that we have used the variable names , , twice, once for each of the two area functions. How does that work?

Consider the following GHCi sequence:

Prelude> let r = 0 Prelude> let area r = pi * r ^ 2 Prelude> area 5 78.53981633974483

It would have been an unpleasant surprise to return for the area because of the earlier definition getting in the way. That does not happen because when you defined the second time you are talking about a different. This may seem confusing, but consider how many people have the name John, and yet for any context with only one John, we can talk about "John" with no confusion. Programming has a notion similar to context, called scope.

We will not explain the technicalities behind scope right now. Just keep in mind that the value of a parameter is strictly what you pass in when you call the function, regardless of what the variable was called in the function's definition. That said, appropriately unique names for variables do make the code easier for human readers to understand.


  1. Variables store values (which can be any arbitrary Haskell expression).
  2. Variables do not change within a scope.
  3. Functions help you write reusable code.
  4. Functions can accept more than one parameter.

We also learned about non-code text comments within a source file.


  1. ↑As this example shows, the names of variables may contain numbers as well as letters. Variables in Haskell must begin with a lowercase letter but may then have any string consisting of letter, numbers, underscore (_) or tick (').

Haskell Assignment Help


A Haskell program consists of a set of function meanings. In Haskell programs, function meanings will extend numerous lines & comprise of abundant components.

Haskell Assignment Help

Haskell is among the leading languages for teaching functional programming, allowing students to compose easier and cleaner code, and to discover the best ways to structure and factor about programs. Haskell is distinct in 2 methods.

It is a pure functional programming language. Then it will return precisely the exact same value both times, if you have a function and you call it two times in 2 various locations with the exact same arguments. Second, Haskell supplies an extremely modern-day type system which integrates functions like typeclasses and generalized algebraic information types.

Haskell is a functional programming language, which is a design of programming where there are no adverse effects, so if you pass the exact same arguments to a function you get the exact same outcome. This leads to some optimizations that can be done by the compiler, and assists in screening. It does make complex programming more than item orientated code.

Haskell is a wide-spectrum language, appropriate for a range of applications. It is especially appropriate for programs which have to be maintainable and extremely flexible.

Much of a software’s life is invested in requirements, upkeep and design, and not in programming. Functional languages are excellent for composing requirements which can in fact be carried out (and thus evaluated and debugged). Such a spec then is the very first prototype of the last program.

The majority of functional languages and Haskell in specific, are highly typed, getting rid of a big class of easy-to-make mistakes at put together time. In certain, strong typing indicates no core disposes! There is merely no possibility of alleviating an integer as a tip, or following a null guideline.

Haskell is lazy. That indicates that unless particularly informed otherwise, Haskell will not carry out functions and determine things till it’s truly compelled to reveal you an outcome.

Haskell is statically typed. When you assemble your program, the compiler understands which piece of code is a number, which is a string and so on. Haskell utilizes a really great type system that has type reasoning.

Haskell is succinct and sophisticated. Haskell programs are normally much shorter than their vital equivalents since it utilizes a lot of high level ideas. And much shorter programs are simpler to preserve than longer ones and have less bugs.

Haskell was made by some truly wise people (with PhDs). When a committee of scientists got together to create a kick-ass language, work on Haskell started in 1987. In 2003 the Haskell Report was released, which specifies a steady variation of the language.

It is function that prints something on the screen is called side-effecting, as it is a function that influences the value of an international variable. Of course, without side impacts every programming language would be worthless; Haskell utilizes a system of monads to occupy all impure calculations from the rest of the program and perform them in the protected method.

Functions of Haskell

– Succinct programs- Due to top-level nature of functional design, the programs composed in Haskell are a lot more succinct than in other languages. The syntax of Haskell has actually been created with succinct programs, couple of keywords & by permitting imprint to be utilized for suggesting the structure of programs.

– Effective type system- A lot of contemporary programming languages consist of some type of type system to identify incompatibility mistakes such as trying to include a character & a number. Haskell has a type system that needs little type info from the developer.

– List understandings- Haskell offers lists as a fundamental principle in the language, together with a effective however basic understanding notation that constructs brand-new lists by choosing & filtering aspects from several existing list.

– Recursive functions- In Haskell, the fundamental system by which looping is accomplished is by utilizing recursive functions.

– Higher-order functions-Haskell is a higher-order functional language that suggests the functions can easily take functions as arguments & produce functions as outcomes.

– Monadic effect- Functions in Haskell are pure functions that take all their inputs as arguments & produce outputs as outcomes.

– Lazy examination- Haskell programs are carried out utilizing a strategy referred to as lazy assessment. The strategy is based upon the concept that no calculation ought to be carried out up until the outcome is really needed.

– Thinking about the programs -Programs in Haskell are pure functions, easy equational thinking can be utilized for performing programs, for changing programs, for showing buildings of programs & even for obtaining programs straight from specifications of their behavior.

Haskell is beneficial for composing robust, high quality and trusted software application. Haskell compiler can likewise carry out optimizations which can not be carried out for other mainstream languages.


Haskell expressions are constantly referentially transparent, that is:

– No anomaly! Everything (variables, information structures …) is immutable.

– Expressions never ever have “adverse effects” (like printing or upgrading worldwide variables to the screen).

– Calling the very same function with the exact same arguments leads to the very same output each time.

Significant updates

– Haskell 98, which was launched in late 1997, consisted of an unique basic library for teaching functions and a structure for future extensions.

– Haskell Prime, which was launched in 2006, considerably upgrading the language spec.

– Haskell 2010 included a function called the foreign function user interface (FFI), which enabled Haskell programs to utilize the capability of other programming languages.

Exactly what makes Haskell unique is how coders have to believe when they utilize the language. Functional programming languages work in extremely various methods than crucial languages where the coder handles lots of low-level information of exactly what takes place in their code and when.

Haskell likewise is utilized in web start-ups where functional programming may work much better than vital programming. Obviously Facebook, Google, NVIDIA, and other business utilize Haskell to develop internal tools utilized in their software application advancement and IT environments.

0 thoughts on “Haskell Assignment”


Leave a Comment

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