2

Write a function that takes the function f and the number n and returns the list [f n, f (n + 1), f (n + 2), f (n + 3), f (n + 4) ... ].

Here is my solution:

func f n = f n : func f (n+1)

But I'm not sure that it is correct. How can I check my implementation?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Silver
  • 101
  • 1
  • 1
  • 6
  • 4
    As you are generating an infinite list, you can use `take` to examine finite prefixes of different lengths. For example, does `take 5 (func (+1) 3) == [4, 5, 6, 7, 8]`? – chepner Mar 02 '20 at 12:30
  • 1
    @Silver I believe your solution is correct (although I think you have a typo — you wrote `funck` instead of `func` in the body of the function). But as @chepner said, you should probably test your function using `take`. – bradrn Mar 02 '20 at 12:36
  • Thanks, I corrected a typo. As for the "take", I took this note. Your opinion was important to me. – Silver Mar 02 '20 at 12:47
  • Another way to write this is `map f [n..]`. A property you could test is:`take k (drop m (func f n)) == take k (func f (n+m))`: the first `k` elements should be the same whether you start at `n+m` or start at `n` and skip `m` elements. – sshine Mar 02 '20 at 13:45

1 Answers1

1

You can give a co-inductive proof. Co-inductive reasoning is similar to inductive reasoning, but it allows for "infinite" structures. It's a natural choice for reasoning about things like data streams and infinite lists.

The property you want func to have is something like

∀ f : Int -> a, ∀ n : Int, ∀ i : Int, (i >= 0 ⟹ (func f n) !! i == f (n + i))

Proving something by co-induction is similar to induction: you assume it as a co-inductive hypothesis for all substructures, and then prove it for the superstructure. Since there is only one definition for func, there is only only such proof obligation.

This means that, if you could prove

∀ f : Int -> a, ∀ n : Int, ∀ i : Int, (i ≥ 0 ⟹ (func f n) !! i == f (n + i))
⟹
∀ f : Int -> a, ∀ n : Int, ∀ i : Int, (i ≥ 0 ⟹ (f n : (func f (n + 1))) !! i == f (n + i))

then you would prove that your function definition is correct.

Since you could actually prove the above statement, your function definition is correct.

Isaac van Bakel
  • 1,772
  • 10
  • 22