Why I can't use matched variable instead of a variable value? - idris

Here is an example from here. The code looks like that:
sum : (single : Bool) -> isSingleton single -> Nat
sum True x = x
sum False [] = 0
sum False (x :: xs) = x + sum False xs
I've tried to use single instead of False in the last line. But it fails. I think the problem is that the type of sum single xs is either Nat or List Nat, but + requires only Nat operands. But we are inside a clause where single equals False either way. Shouldn't Idris infer it? Why I can't use single here? Is there some reason for it?
Here is the error:
main.idr:14:23-41:
|
14 | sum False (x :: xs) = x + (sum single xs)
| ~~~~~~~~~~~~~~~~~~~
When checking right hand side of Main.sum with expected type
Nat
When checking argument single to Main.sum:
No such variable single
Upd:
It looks like that the problem here is that I can't directly access the variable from type definition. Then I've tried to use implicit arguments like that:
sum : (single : Bool) -> isSingleton single -> Nat
sum True x = x
sum False [] = 0
sum {single} False (x :: xs) = x + sum single xs
It doesn't help either. Maybe I'm using it wrong. Also I've tried the simplest possible variation like that:
sum : (single: Bool) -> isSingleton single -> Nat
sum s list = case s of
True => list
False => case list of
[] => 0
(x::xs) => x + (sum s xs)
But it doesn't compile either:
|
16 | (x::xs) => x + (sum s xs)
| ~~~~~~~~
When checking right hand side of Main.case block in case block in sum at main.idr:12:19 at main.idr:14:19-22 with expected type
Nat
When checking an application of Main.sum:
Type mismatch between
List Nat (Type of xs)
and
isSingleton s (Expected type)
It looks a bit weird for me, because from one point Idris could prove many interesting and complex things, and from another such a simple thins is unavailable. Or maybe I'm doing it wrong.

It's not so much that it can't infer the type of single, as single isn't in scope on the RHS. You could use a named pattern with single on the LHS
sum : (single : Bool) -> isSingleton single -> Nat
sum True x = x
sum False [] = 0
sum single#False (x :: xs) = x + sum single xs
I can't see a way to avoid the named pattern in this case and just use
sum single (x :: xs) = x + sum single xs
as Idris doesn't infer it's a List Nat without the False. I get
|
8 | sum single (x :: xs) = x + sum single xs
| ~~~~~~~~~~~~~~~~~~~~
When checking left hand side of Main.sum:
When checking an application of Main.sum:
Can't disambiguate since no name has a suitable type:
Prelude.List.::, Prelude.Stream.::

Related

How to match on all integers in a range in a total function?

Let's say we want to check the parity of an Int:
data Parity = Even | Odd
It would be pretty easy for Nat:
parity0: Nat -> Parity
parity0 Z = Even
parity0 (S k) = case parity0 k of
Even => Odd
Odd => Even
The first attempt to implement that for Int:
parity1: Int -> Parity
parity1 x = if mod x 2 == 0 then Even else Odd
This function is not total:
Main.parity1 is possibly not total due to: Prelude.Interfaces.Int implementation of Prelude.Interfaces.Integral
It makes sense because mod is not total for Int. (Although I'm not sure how I could know it in advance. The REPL shows that mod is total. Apparently, you can use a partial function to implement a total function of an interface? Strange.)
Next, I try to use DivBy view:
parity2: Int -> Parity
parity2 x with (divides x 2)
parity2 ((2 * div) + rem) | (DivBy prf) =
if rem == 0 then Even else Odd
This function works and is total, but the implementation is error-prone and doesn't scale to cases where we have multiple possible values. I'd like to assert that rem can only be 0 or 1. So I attempt to use case on rem:
parity3: Int -> Parity
parity3 x with (divides x 2)
parity3 ((2 * div) + rem) | (DivBy prf) = case rem of
0 => Even
1 => Odd
This function also works but is not total. How can I use prf provided by DivBy to convince the compiler that it's total? How can I use this prf in general?
Would using Integer or some other type make this problem easier to solve?
And there is another very concerning thing. I tried to case-split on prf and discovered that the following function is total:
parity4: Int -> Parity
parity4 x with (divides x 2)
parity4 ((2 * div) + rem) | (DivBy prf) impossible
Is that a bug? I can use this function to produce a runtime crash in a program that only contains total functions.

How do you operate on dependent pairs in a proof?

This is a follow up to this question. Thanks to Kwartz I now have a state of the proposition if b divides a then b divides a * c for any integer c, namely:
alsoDividesMultiples : (a, b, c : Integer) ->
DivisibleBy a b ->
DivisibleBy (a * c) b
Now, the goal has been to prove that statement. I realized that I do not understand how to operate on dependent pairs. I tried a simpler problem, which was show that every number is divisible by 1. After a shameful amount of thought on it, I thought I had come up with a solution:
-- All numbers are divisible by 1.
DivisibleBy a 1 = let n = a in
(n : Integer ** a = 1 * n)
This compiles, but I was had doubts it was valid. To verify that I was wrong, it changed it slightly to:
-- All numbers are divisible by 1.
DivisibleBy a 1 = let n = a in
(n : Integer ** a = 2 * n)
This also compiles, which means my "English" interpretation is certainly incorrect, for I would interpret this as "All numbers are divisible by one since every number is two times another integer". Thus, I am not entirely sure what I am demonstrating with that statement. So, I went back and tried a more conventional way of stating the problem:
oneDividesAll : (a : Integer) ->
(DivisibleBy a 1)
oneDividesAll a = ?sorry
For the implementation of oneDividesAll I am not really sure how to "inject" the fact that (n = a). For example, I would write (in English) this proof as:
We wish to show that 1 | a. If so, it follows that a = 1 * n for some n. Let n = a, then a = a * 1, which is true by identity.
I am not sure how to really say: "Consider when n = a". From my understanding, the rewrite tactic requires a proof that n = a.
I tried adapting my fallacious proof:
oneDividesAll : (a : Integer) ->
(DivisibleBy a 1)
oneDividesAll a = let n = a in (n : Integer ** a = b * n)
But this gives:
|
12 | oneDividesAll a = let n = a in (n : Integer ** a = b * n)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When checking right hand side of oneDividesAll with expected type
DivisibleBy a 1
Type mismatch between
Type (Type of DPair a P)
and
(n : Integer ** a = prim__mulBigInt 1 n) (Expected type)
Any help/hints would be appreciated.
First off, if you want to prove properties on number, you should use Nat (or other inductive types). Integer uses primitives that the argument can't argue further than prim__mulBigInt : Integer -> Integer -> Integer; that you pass two Integer to get one. The compiler doesn't know anything how the resulting Integer looks like, so it cannot prove stuff about it.
So I'll go along with Nat:
DivisibleBy : Nat -> Nat -> Type
DivisibleBy a b = (n : Nat ** a = b * n)
Again, this is a proposition, not a proof. DivisibleBy 6 0 is a valid type, but you won't find a proof : Divisible 6 0. So you were right with
oneDividesAll : (a : Nat) ->
(DivisibleBy a 1)
oneDividesAll a = ?sorry
With that, you could generate proofs of the form oneDividesAll a : DivisibleBy a 1. So, what comes into the hole ?sorry? :t sorry gives us sorry : (n : Nat ** a = plus n 0) (which is just DivisibleBy a 1 resolved as far as Idris can). You got confused on the right part of the pair: x = y is a type, but now we need a value – that's what's your last error cryptic error message hints at). = has only one constructor, Refl : x = x. So we need to get both sides of the equality to the same value, so the result looks something like (n ** Refl).
As you thought, we need to set n to a:
oneDividesAll a = (a ** ?hole)
For the needed rewrite tactic we check out :search plus a 0 = a, and see plusZeroRightNeutral has the right type.
oneDividesAll a = (a ** rewrite plusZeroRightNeutral a in ?hole)
Now :t hole gives us hole : a = a so we can just auto-complete to Refl:
oneDividesAll a = (a ** rewrite plusZeroRightNeutral a in Refl)
A good tutorial on theorem proving (where it's also explained why plus a Z does not reduce) is in the Idris Doc.

Understanding 'impossible'

Type-Driven Development with Idris presents:
twoPlusTwoNotFive : 2 + 2 = 5 -> Void
twoPlusTwoNotFive Refl impossible
Is the above a function or value? If it's the former, then why is there no variable arguments, e.g.
add1 : Int -> Int
add1 x = x + 1
In particular, I'm confused at the lack of = in twoPlusTwoNotFive.
impossible calls out combinations of arguments which are, well, impossible. Idris absolves you of the responsibility to provide a right-hand side when a case is impossible.
In this instance, we're writing a function of type (2 + 2 = 5) -> Void. Void is a type with no values, so if we succeed in implementing such a function we should expect that all of its cases will turn out to be impossible. Now, = has only one constructor (Refl : x = x), and it can't be used here because it requires ='s arguments to be definitionally equal - they have to be the same x. So, naturally, it's impossible. There's no way anyone could successfully call this function at runtime, and we're saved from having to prove something that isn't true, which would have been quite a big ask.
Here's another example: you can't index into an empty vector. Scrutinising the Vect and finding it to be [] tells us that n ~ Z; since Fin n is the type of natural numbers less than n there's no value a caller could use to fill in the second argument.
at : Vect n a -> Fin n -> a
at [] FZ impossible
at [] (FS i) impossible
at (x::xs) FZ = x
at (x::xs) (FS i) = at xs i
Much of the time you're allowed to omit impossible cases altogether.
I slightly prefer Agda's notation for the same concept, which uses the symbol () to explicitly pinpoint which bit of the input expression is impossible.
twoPlusTwoNotFive : (2 + 2 ≡ 5) -> ⊥
twoPlusTwoNotFive () -- again, no RHS
at : forall {n}{A : Set} -> Vec A n -> Fin n -> A
at [] ()
at (x ∷ xs) zero = x
at (x ∷ xs) (suc i) = at xs i
I like it because sometimes you only learn that a case is impossible after doing some further pattern matching on the arguments; when the impossible thing is buried several layers down it's nice to have a visual aid to help you spot where it was.

Idris: function works with Nat parameter and fails type checking with Integer parameter

I am new to Idris. I am experimenting with types and my task is to make an "onion": a function that takes two arguments: a number and whatever and puts whatever into List nested such number of times.
For example, the result for mkOnion 3 "Hello World" should be [[["Hello World"]]].
I've made such a function, this is my code:
onionListType : Nat -> Type -> Type
onionListType Z b = b
onionListType (S a) b = onionListType a (List b)
mkOnionList : (x : Nat) -> y -> onionListType x y
mkOnionList Z a = a
mkOnionList (S n) a = mkOnionList n [a]
prn : (Show a) => a -> IO ();
prn a = putStrLn $ show a;
main : IO()
main = do
prn $ mkOnionList 3 4
prn $ mkOnionList 2 'a'
prn $ mkOnionList 5 "Hello"
prn $ mkOnionList 0 3.14
The result of program work:
[[[4]]]
[['a']]
[[[[["Hello"]]]]]
3.14
This is exactly what I need.
But when I do the same, but change Nat to Integer like this
onionListTypeI : Integer -> Type -> Type
onionListTypeI 0 b = b
onionListTypeI a b = onionListTypeI (a-1) (List b)
mkOnionListI : (x : Integer) -> y -> onionListTypeI x y
mkOnionListI 0 a = a
mkOnionListI n a = mkOnionListI (n-1) [a]
I get an error:
When checking right hand side of mkOnionListI with expected type
onionListTypeI 0 y
Type mismatch between
y (Type of a) and
onionListTypeI 0 y (Expected type)
Why does type checking fails?
I think this is because Integer can take negative values and Type can't be computed in case of negative values. If I am right, how does the compiler understand this?
You are right, that the type can't be computed. But that is because the onionListTypeI is not total. You can check this in the REPL
*test> :total onionListTypeI
Main.onionListTypeI is possibly not total due to recursive path:
Main.onionListTypeI, Main.onionListTypeI
(Or even better, demanding %default total in the source code, which would raise an error.)
Because the type constructor is not total, the compiler won't normalize onionListTypeI 0 y to y. It is not total, because of the case onionListTypeI a b = onionListTypeI (a-1) (List b). The compiler does only know that subtracting 1 from an Integer results to an Integer, but not which number exactly (unlike when doing it with a Nat). This is because arithmetic with Integer, Int, Double and the various Bits are defined with primary functions like prim__subBigInt. And if these functions wouldn't be blind, the compiler should have a problem with negative values, like you assumed.

Idris: Force vector sums to be equal

I am trying to learn Idris by rebuilding (in a more simple manner) some stuff we recently did at work.
I would like to have a data type that models a general ledger with a vector of credits and a vector of debits. I have gotten this far:
data GL : Type where
MkGL : (credits : Vect n Integer) ->
(debits : Vect m Integer) ->
(sum credits = sum debits) ->
GL
emptyGL : GL
emptyGL = MkGL [] [] Refl
but I am not sure how to add records to an already existing GL.
With a function like
addTransactions : GL -> (Vect j Integer) -> (Vect k Integer) -> Maybe GL
How do I check/enforce that the new GL plays by the rules?
I think the way I would handle this situation would be to create a new datatype to represent vectors of integers with a given total value, like so:
||| A Vector of Integers with a given sum total
data iVect : Nat -> Integer -> Type where
iZero : iVect 0 0
iAdd : (x : Integer) -> iVect n y -> iVect (S n) (y + x)
data GL : Type where
MkGL : (credits : iVect n s) ->
(debits : iVect m s) ->
GL
emptyGL : GL
emptyGL = MkGL iZero iZero
You may want to define an additional function for more convenient updating of a GT but you get the idea. Now the equality of the credits and debits is enforced by the type system without creating a burdensome obligation to explicitly prove that the sums of two arbitrary vectors are in fact equal every time you want to construct a GL. They amount to the same thing anyway, but what I'm describing is a much more practical way to do it.