Skip to content

Instantly share code, notes, and snippets.

@JonNorman
Created November 9, 2018 16:57
Show Gist options
  • Save JonNorman/2ac79d0f6ef3c690ceb76cc0fa3dd2f4 to your computer and use it in GitHub Desktop.
Save JonNorman/2ac79d0f6ef3c690ceb76cc0fa3dd2f4 to your computer and use it in GitHub Desktop.
Exercises to go through in the class or at home for week 5 - focussing on writing our own version of `Option`
/**
Class / Takeaway exercises:
We are going to write own version of the Option class, called MaybeInt which
will represent an Int that might be present or might not.
We should try and replicate as much of the same behaviour from Option as possible.
For now let's call our two possibilities:
`ActualInt(Int)` and `NoInt`, we might create a MaybeInt like so:
```
val maybe2: MaybeInt = Actual(2)
val maybe0: MaybeInt = Actual(0)
val maybe6: MaybeInt = NoInt
```
Note: The exercise code snippets below assume that the field on an `ActualInt` is called `value`
Each exercise requires you to replace the ??? with an implementation that statisfies the description and types
of the function.
*/
/**
1. Create a definition for a `MaybeInt` and the two possible types: `ActualInt` and `NoInt`
*/
/**
2. Implement the `exists` function: it returns `true` if `m` is an `Actual`, and `false` otherwise.
*/
def isDefined(m: MaybeInt): Boolean = ???
assert(!isDefined(Missing))
assert(isDefined(MaybeInt(29)))
/** note that `assert` expects an expression to evaluate - for functions that already return a `Boolean`
* we can just pass this value straight into the assert - there is no need for `result == true` or ` == false`.
* */
/**
3. Implement the function `exists` function: it returns
`true` if the supplied `MaybeInt` is an `ActualInt` AND a supplied function applied to the value in the `MaybeInt` returns `true`, and
`false` otherwise
*/
def exists(m: MaybeInt, condition: Int => Boolean): Boolean = ???
assert(!exists(Missing, _ > 5))
assert(!exists(ActualInt(30), _ > 50))
assert(exists(ActualInt(60), _ > 50))
/**
4. Implement the `map` function: if the supplied MaybeInt is an ActualInt then `map` applies the supplied
function `f` to this value and returns that as an `ActualInt`, otherwise `map` returns `Missing`
*/
def map(m: MaybeInt, f: Int => Int): MaybeInt = ???
assert(map(Missing, _ * 2) == Missing)
assert(map(ActualInt(10), _ * 2) == ActualInt(20))
assert(map(ActualInt(123), int => int - 10) == ActualInt(113))
/**
5. Implement the `getOrElse` function: if the supplied `MaybeInt` is an `ActualInt` then `getOrElse` returns the `Int`
otherwise it returns the fallback `Int` value.
*/
def getOrElse(m: MaybeInt, fallback: Int): Int = ???
assert(getOrElse(Missing, 0) == 0)
assert(getOrElse(ActualInt(4), 0) == 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment