Skip to content
Snippets Groups Projects
Commit d1a253e2 authored by kiady.arintsoa's avatar kiady.arintsoa :man_with_turban_tone2:
Browse files

Ex3 and scanRight example

parent 771ac219
No related branches found
No related tags found
No related merge requests found
# Exercise 3
## 1. Reduce the following expressions. Assume these rules, and indicate at each step which rule is used
### a) `if iszero succ succ 0 then succ succ succ 0 else succ 0`
| State | Rule |
|:------|:-----|
|`if false then succ succ succ 0 else succ 0` | `iszero succ nv1 -> false`|
|`succ 0` | `if false then t1 else t2 -> t2`|
### b) `succ succ if iszero succ 0 then succ 0 else succ succ 0`
| State | Rule |
|:------|:-----|
|`succ succ if false then succ 0 else succ succ 0` | `iszero succ nv1 -> false`|
|`succ succ succ succ 0` | `if false then t1 else t2 -> t2`|
### c) `iszero if iszero pred succ pred succ 0 then if true then succ 0 else 0 else 0`
| State | Rule |
|:------|:-----|
| `iszero if iszero pred succ 0 then if true then succ 0 else 0 else 0` | `pred succ nv1 -> nv1` |
| `iszero if iszero 0 then if true then succ 0 else 0 else 0` | `pred succ nv1 -> nv1` |
| `iszero if true then if true then succ 0 else 0 else 0` | `iszero 0 -> true` |
| `iszero if true then succ 0 else 0` | `if true then t1 else t2 -> t1` |
| `iszero succ 0` | `if true then t1 else t2 -> t1` |
| `false` | `iszero succ nv1 -> false` |
## 2. Assuming the following typing rules, determine if the nest expressions are well typed. Jusify your answers.
### a) `if iszero succ succ succ 0 then false else iszero succ 0 : Bool`
| Expression | Type |
|:------|:-----|
`succ succ succ 0` | Nat
`succ 0` | Nat
`iszero [Nat]` | Bool
Well typed, the rule `if [Bool] then [T] else [T]` is respected with `T = Bool`.
### b) `iszero if iszero pred succ pred succ 0 then if true then succ 0 else 0 else 0 : Nat`
Even before starting, we can see that the predicted type is `Nat` when the expression is `iszero [...]` it is therefore wrong.
The `if`s are well typed. The structure in each case is `if [Bool] then [Nat] else [Nat]`.
## 3. Reduce the following lambda expresions :
### a) `(λx.λy.x y y) (λz.z) a`
| Step | Expr |
|-----:|:-----|
|0|`(λx.λy.x y y) (λz.z) a`|
|1|`(λy.λz.z y y) a`|
|2|`λz.z a a`|
### b) `(λx.x) (λy.y y) f`
| Step | Expr |
|-----:|:-----|
|0|`(λx.x) (λy.y y) f`|
|1|`(λy.y y) f`|
|2|`f f`
package scanRightExample
@main
def main() = {
// From https://stackoverflow.com/questions/17408880/reduce-fold-or-scan-left-right
val abc = List("A", "B", "C")
def add(res: String, x: String) = {
// println(s"op: $res + $x = ${res + x}")
res + x
}
println(abc.scanLeft("z")(add))
println(abc.scanRight("z")(add))
val funcs = List(
(x: Int) => x + 1,
(x: Int) => x * 2,
(x: Int) => x * x
)
println(funcs.scanLeft(2)((v, f) => f(v)))
println(funcs.reverse.scanLeft(2)((v, f) => f(v)))
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment