Undefined

Consider a function that takes three integers but hasn’t been defined:

​  addThree :: ​ Int ​ -> ​ Int ​ -> ​ Int ​ -> ​ Int ​

There are several different ways that you could write a function like this. For example, here are two possible definitions:

​  ​ -- definition 1 ​
​  addThree = undefined
​  
​  ​ -- definition 2 ​
​  addThree a b c = undefined

There are many other ways we could use undefined to write a version of addThree that type checks. Why are there so many different versions?

Understanding Functions by Their Type

The behavior of the following functions from base can be easily predicted based on their type. Review the type of each of these functions and try to guess at how they are implemented. Use ghci to see if you were right. Are there other ways you could have implemented them? Why or why not?

  • Data.Tuple.swap :: (a,b) -> (b,a)
  • concat :: [[a]] -> [a]
  • id :: a -> a

Filling In Type Holes

Consider the following example code:

​  mapApply :: [a -> b] -> [a] -> [b]
​  mapApply toApply =
​  concatMap (​ \ ​input -> map ($ input) toApply)
​  
​  example :: [​ Int ​] -> ​ String ​
​  example = mapApply undefined
​  ​ where ​
​  letters :: [​ Char ​]
​  letters = [​ 'a' ​..​ 'z' ​]
​  
​  lookupLetter :: ​ Int ​ -> ​ Char ​
​  lookupLetter n = letters !! n
​  
​  offsets :: [​ Int ​ -> ​ Int ​]
​  offsets = [rot13, swap10, mixupVowels]
​  
​  rot13 :: ​ Int ​ -> ​ Int ​
​  rot13 n = (n + 13) `rem` 26
​  
​  swap10 :: ​ Int ​ -> ​ Int ​
​  swap10 n
​  | n <= 10 = n + 10
​  | n <= 20 = n - 10
​  | otherwise = n
​  
​  mixupVowels :: ​ Int ​ -> ​ Int ​
​  mixupVowels n =
​  ​ case ​ n ​ of ​
​  0 -> 8
​  4 -> 14
​  8 -> 20
​  14 -> 0
​  20 -> 4
​  n' -> n'

Try to fill in the value of undefined so that you get the following output:

​  ​ λ ​ example [5..15]
​  ​ "spftqgurhvsuwtjxukyblzcmadnbeacfp" ​

Use type holes to help you figure out the type of the value you’ll need to use.

Copyright © 2023, The Pragmatic Bookshelf.