Elm exercise solutions

Want to write Elm at work? I am looking for Elm developers at diesdas.digital in Berlin. 🙂


The following exercises are taken from this page. Solutions are written in Elm 0.15.1.

1. Sum all of the elements of a tree.

sum : Tree Int -> Int
sum tree =
  case tree of
    Empty -> 0
    Node value left right ->
      value + (sum left) + (sum right)

2. Flatten a tree into a list.

Using List.append

import List exposing (append)
flatten : Tree a -> List a
flatten tree =
  case tree of
    Empty -> []
    Node value left right ->
      value :: append (flatten left) (flatten right)

Using List.concat

import List exposing (concat)
flatten : Tree a -> List a
flatten tree =
  case tree of
    Empty -> []
    Node value left right ->
      concat [ [value], flatten left, flatten right ]

3. Check to see if an element is in a given tree.

isElement : a -> Tree a -> Bool
isElement element tree =
  case tree of
    Empty -> False
    Node value left right ->
      if | value == element -> True
         | otherwise -> (isElement element left || isElement element right)

Instead of otherwise you could also write:

if | value == element -> True
   | value /= element -> (isElement element left || isElement element right)

Make sure to call it like this: display "isElement" (isElement 2) t2

4. Check to see if an element is in a given tree.

fold : (a -> b -> b) -> b -> Tree a -> b
fold func initialValue tree =
  case tree of
    Empty -> initialValue
    Node value left right ->
      func value (fold func (fold func initialValue right) left)

Alternative using local variables

fold : (a -> b -> b) -> b -> Tree a -> b
fold func initialValue tree =
  case tree of
    Empty -> initialValue
    Node value left right ->
      let sum = fold func rightSum left
          rightSum = fold func initialValue right
      in
        func value sum
Share on twitter