Programming in Haskell exercises (2)

Working on exercises of Chapter 2 First steps

拇指 muzhi.com
Analytics Vidhya
Published in
4 min readDec 30, 2019

--

code tested on this mac

Change terminal prompt and ghci prompt. Let ghci support multiple lines.

  1. Work through the examples from this chapter using GHCi.

Function head, tail, take, length, sum, product and reverse:

Haskell source code in file test.hs:

Edit test.hs in another terminal. Update code and save with vim command :w.

Reload test.hs using ghci command :reload or :r.

test.hs with indentation sample:

Reload and try:

Use curly braces:

Reload and try:

Put everything on a single line:

Reload and try:

Single line comment and block comment:

Function double was commented out:

2. Parenthesize the following numeric expressions:
2 ^ 3 * 4
2 * 3 + 4 * 5
2 + 3 * 4 ^ 5

3. The script below contains three syntactic errors. Correct these errors and then check that your script works properly using GHCi.
N = a ‘div’ length xs

N should be n

‘ should be `

xs should be aligned with a of the previous line

3 errors corrected:

4. The library function last selects the last element of a non-empty list; for example last [1,2,3,4,5] = 5. Show how the function last could be defined in terms of the other library function introduced in this chapter. Can you think of another possible definition?

Here is a different way using index:

5. The library function init removes the last element from a non-empty list; for example, init [1,2,3,4,5] = [1,2,3,4]. Show how init could similarly be defined in two different ways.

Here is a different way using reverse and tail:

--

--