Tonλ's blog May the λ be with you

Programming in haskell - Ch2 - First steps

by @ardumont on

Parenthesis

Parenthesise the following arithmetic expressions:

  • 2 ^ 3 ∗ 4
  • 2 ∗ 3 + 4 ∗ 5
  • 2 + 3 ∗ 4 ^ 5
2^3*4 = (2^3)*4

2∗3+4∗5 = (2*3)+(4*5)

2+3*4^5 = 2+(3*(4^5))

Execution

Work through the examples from this chapter using Hugs.

2^3*4 =  32

2∗3+4∗5 = 26

2+3*4^5 = 3074

Fix errors

The script below contains three syntactic errors. Correct these errors and then check that your script works properly using Hugs.

N = a 'div' length xs
    where
      a = 10
      xs = [1, 2, 3, 4, 5]

Fixed:

n = a `div` length xs
    where
      a  = 10
      xs = [1, 2, 3, 4, 5]

Definition of last

Show how the library function last that selects the last element of a non- empty list could be defined in terms of the library functions introduced in this chapter.

We can basically return the sequence and take the first element.

last1 :: [a] -> a
last1 xs = head (reverse xs)

Can you think of another possible definition?

We can take the ith element where ith element is the length of the list.

last2 :: [a] -> a
last2 xs = xs !! (length xs - 1)

Or we can make a sequence by dropping all elements but the last one and then retrieve the first element of such sequence:

last3 :: [a] -> a
last3 xs = head (drop i xs)
           where
             i = length xs - 1

init

Show how the library function init that removes the last element from a non-empty list could similarly be defined in two different ways.

We can take all the elements from the list except the last one.

init1 :: [a] -> [a]
init1 xs = take (length xs - 1) xs

Or reverse the list, remove the first element, then return the list again.

init2 :: [a] -> [a]
init2 xs  = reverse (drop 1 (reverse xs))

And as for the drop 1 call goes, we can replace this by the tail call:

init3 :: [a] -> [a]
init3 xs  = reverse (tail (reverse xs))

Source

Latest posts