0

I have the function:

natListLast : List ℕ → ℕ
natListLast []            = 0
natListLast nats@(x ∷ xs) = v.last (v.fromList nats)

When I do

_ : natListLast (2 l.∷ l.[] l.++ 1 l.∷ l.[]) ≡ 1
_ = refl

I don't get any error.

But when I try to generalize this to an arbitrary List nat like so:

natListConcatLast : (nats : List ℕ) → natListLast (nats l.++ 1 l.∷ l.[]) ≡ 1
natListConcatLast [] = refl
natListConcatLast nats@(x ∷ xs) = ?

I'm not sure what to replace ? with.

I tried starting with begin:

natListConcatLast : (nats : List ℕ) → natListLast (nats l.++ 1 l.∷ l.[]) ≡ 1
natListConcatLast [] = refl
natListConcatLast nats@(x ∷ xs) =
  begin
    natListLast (nats l.++ 1 l.∷ l.[])
  ≡⟨⟩
    v.last (v.fromList ((x l.∷ xs) l.++ 1 l.∷ l.[]))
  ≡⟨⟩
    ?
  ≡⟨⟩
    1
  ∎

but I get this error:

1 !=
(last (fromList ((x List.∷ xs) l.++ 1 List.∷ List.[]))
 | initLast (fromList ((x List.∷ xs) l.++ 1 List.∷ List.[])))
of type ℕ
when checking that the expression 1 ∎ has type
last (fromList ((x List.∷ xs) l.++ 1 List.∷ List.[])) ≡ 1

I'm not sure how to interpret this error. I'm not sure how to deal with | initLast.

Thanks!

fsuna064
  • 195
  • 1
  • 7
  • Do you have any good reason for wanting to define `natListLast` via `Data.Vec.last` instead of writing it directly? – Cactus Nov 16 '20 at 06:20
  • I needed it because I was getting the error `l.foldr (λ _ → suc) 0 (nats l.++ 1 List.∷ List.[]) != suc _n_199 of type ℕ when checking that the expression fromList (nats l.++ 1 List.∷ l.[]) has type Vec ℕ (1 + _n_199)` if I used `v.last (v.fromList <...>))` directly – fsuna064 Nov 16 '20 at 17:22

1 Answers1

2

I suggest the following solution:

open import Data.List
open import Data.Nat
open import Relation.Binary.PropositionalEquality using (_≡_ ; refl)

natListLast : List ℕ → ℕ
natListLast [] = 0
natListLast (x ∷ []) = x
natListLast (_ ∷ y ∷ l) = natListLast (y ∷ l)

natListConcatLast : ∀ l → natListLast (l ++ [ 1 ]) ≡ 1
natListConcatLast [] = refl
natListConcatLast (_ ∷ []) = refl
natListConcatLast (_ ∷ _ ∷ l) = natListConcatLast (_ ∷ l)
MrO
  • 1,291
  • 7
  • 14