Why do Dafny inductive predicates use ordinals? - induction

Section 11.1.2 of the Dafny Reference Manual provides these examples of extreme predicates:
inductive predicate g(x: int) { x == 0 || g(x-2) }
copredicate G(x: int) { x == 0 || G(x-2) }
Section 11.1.3 then gives a few example proofs about them:
lemma EvenNat(x: int)
requires g(x)
ensures 0 <= x && x % 2 == 0
{
var k: nat :| g#[k](x); EvenNatAux(k, x);
}
lemma EvenNatAux(k: nat, x: int)
requires g#[k](x)
ensures 0 <= x && x % 2 == 0
{
if x == 0 {
} else {
EvenNatAux(k-1, x-2);
}
}
lemma Always(x: int)
ensures G(x)
{ forall k: nat { AlwaysAux(k, x); } }
lemma AlwaysAux(k: nat, x: int)
ensures G#[k](x)
{ }
These lemmas don't type-check. The prefix-call notation g#[k](x) triggers this error:
type mismatch for argument 0 (function expects ORDINAL, got nat)
The corresponding inductive lemma and colemma examples in section 11.1.4 work fine. My question is about 11.1.3.
This must have changed. Why are the ordinals a better choice than the naturals? Is it possible for the two types to produce different fix points, and if so, is the one produced for the ordinals really the least fix point?
I'm a bit worried that I might define an inductive predicate for something like
inductive predicate isProvable(x) {
isAxiom(x) || exists w :: isProvable(w) && implies(w, x)
}
and have it turn out to mean something preposterous, permitting infinite chains of implies because the index is an ordinal. Am I wrong to worry?

Related

Haskell Type errors

First day learning haskell, and coming from a python background I'm really having trouble debugging when it comes to type; Currently I'm working on a simple function to see if a number is a prime;
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0 then False else True
It works when I have a specific number instead of the generic P, but no matter what I try (and I've tried a lot, including just moving onto different problems) I always get some kind of error regarding type. For this current iteration, I'm getting the error
<interactive>:149:1: error:
* Ambiguous type variable `a0' arising from a use of `prime'
prevents the constraint `(RealFrac a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance RealFrac Double -- Defined in `GHC.Float'
instance RealFrac Float -- Defined in `GHC.Float'
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the expression: prime 2
In an equation for `it': it = prime 2
<interactive>:149:7: error:
* Ambiguous type variable `a0' arising from the literal `2'
prevents the constraint `(Num a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Num Integer -- Defined in `GHC.Num'
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the first argument of `prime', namely `2'
In the expression: prime 2
In an equation for `it': it = prime 2
If someone could, as well as debugging this particular program, give me a heads up on how to think of haskell types, I'd be incredibly grateful. I've tried looking at learnyouahaskell but so far I've had no luck applying that.
In short: by using mod, floor, and (**) all at the same time, you restrict the type of p a lot, and Haskell fails to find a numerical type to call prime.
The main problem here is in the iterable of your list comprehension:
[2..(floor(p**0.5))]
Here you call p ** 0.5, but since (**) has type (**) :: Floating a => a -> a -> a, that thus means that p has to be an instance of a type that is an instance of the Floating typeclass, for example a Float. I guess you do not want that.
Your floor :: (RealFrac a, Integral b) => a -> b even makes it worse, since now p also has to be of a type that is an instance of the RealFrac typeclass.
On the other hand, you use mod :: Integral a => a -> a -> a, so it means that your p has to be Floating, as well as Integral, which are rather two disjunctive sets: although strictly speaking, we can define such a type, it is rather weird for a number to be both Integral and Floating at the same type. Float is for instance a Floating number, but not Integral, and Int is Integral, but not a Floating type.
We have to find a way to relax the constraints put on p. Since usually non-Integral numbers are no primes at all, we better thus aim to throw out floor and (**). The optimization to iterate up to the square root of p is however a good idea, but we will need to find other means to enforce that.
One way to do this is by using a takeWhile :: (a -> Bool) -> [a] -> [a] where we take elements, until the square of the numbers is greater than p, so we can rewrite the [2..(floor(p**0.5))] to:
takeWhile (\x -> x * x <= p) [2..]
We even can work only with odd elements and 2, by writing it as:
takeWhile (\x -> x * x <= p) (2:[3, 5..])
If we test this with a p that is for instance set to 99, we get:
Prelude> takeWhile (\x -> x * x <= 99) (2:[3, 5..])
[2,3,5,7,9]
If we plug that in, we relaxed the type:
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x <- takeWhile (\x -> x * x <= p) (2:[3, 5..])]) > 0 then False else True
we actually relaxed it enough:
Prelude> :t prime
prime :: Integral a => a -> Bool
and we get:
Prelude> prime 23
True
But the code is very ugly and rather un-Haskell. First of all, you here use maximum as a trick to check if all elements satisfy a predicate. But it makes no sense to do that this way: from the moment one of the elements is dividable, we know that the number is not prime. So we can better use the all :: (a -> Bool) -> [a] -> Bool function. Furthermore conditions are usually checked by using pattern matching and guards, so we can write it like:
prime :: Integral a => a -> Bool
prime n | n < 2 = False
| otherwise = all ((/=) 0 . mod n) divisors
where divisors = takeWhile (\x -> x * x <= n) (2:[3, 5..])
Your code can be simplified as
prime p = if p == 1 then False else
if p == 2 then True else
if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0
then False else True
=
prime p = if p == 1 then False else
if p == 2 then True else
not (maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] > 0 )
=
prime p = not ( p == 1 ) &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] <= 0 )
=
prime p = p /= 1 &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] == -1 )
=~
prime p = p == 2 || p > 2 && null [x | x <- [2..floor(p**0.5)], p `mod` x == 0]
(convince yourself in the validity of each transformation).
This still gives us a type error of course, because (**) :: Floating a => a -> a -> a and mod :: Integral a => a -> a -> a are conflicting. To counter that, just throw a fromIntegral in there:
isPrime :: Integral a => a -> Bool
isPrime p = p == 2 ||
p > 2 && null [x | x <- [2..floor(fromIntegral p**0.5)], p `mod` x == 0]
and it's working:
~> filter isPrime [1..100]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

how to do bit shifts and masks in haskell?

I'm writing a routine to determine whether the high 16 bits of a 32-bit integer have more bits set, or the low bits.
In C, I would write this:
bool more_high_bits(int a) {
if ((a >> 16) == 0) return false; // no high bits
if ((a & 0xFFFF) == 0) return true; // no low bits
// clear one high bit and one low bit, and ask again
return more_high_bits(a&(a - 0x10001));
}
So in Haskell, I'm trying this:
more_high_bits a=if (a `shiftR` 16) /= 0 then 0 else
if ((.&.) a 65535) /= 0 then 1 else
more_high_bits((.&.) a (a-65537))
But it just times out.
What am I doing wrong? What's the more idiomatic way to do this? Please don't code away the shift or the & because I'd like to know how I "should" be using these.
Addendum: I tried this code out on an haskell compiler:
http://www.tutorialspoint.com/compile_haskell_online.php
import Data.Bits
g a=if (a `shiftR` 16) == 0 then 0 else
if ((.&.) a 65535) == 0 then 1 else
g((.&.) a (a-65537))
main = print (g(237))
But it tells me "No instance for (Bits a0) arising from a use of 'g'
The type variable 'a0' is ambiguous"
What is "a0"??
Here's a pretty direct translation of your C code to Haskell:
import Data.Word
import Data.Bits
more_high_bits :: Word32 -> Bool
more_high_bits a
| (a `shiftR` 16) == 0 = False
| (a .&. 0xFFFF) == 0 = True
| otherwise = more_high_bits (a .&. (a - 0x10001))
Your attempt has /= where the C version has ==, which inverts the condition.
a0 is the type variable that the type checker automatically created for your use of g 237. It doesn't know which type you mean because 237 could be any numeric type at all, and g works with all numbers that support bitwise operations and equality. The list of types you could have meant includes (but is not limited to) Int, Integer, Word, ...

Ambiguous occurrence '=='

I'm just learning Haskell and still trying to figure out how things work.
So I'm creating a list class that can hold a mixture of Int and Char.
data Algebra = Empty
| Nmbr Int Algebra
| Smbl Char Algebra
Then I try to make it an instance of Eq
instance Eq Algebra where
Empty == Empty = True
(Nmbr x xl) == (Nmbr y yl) = (x == y) && (xl==yl)
(Smbl x xl) == (Smbl y yl) = (x == y) && (xl==yl)
_ == _ = False
and I get an Ambiguous occurrence == compile error. It can't tell the difference between Main.== and Prelude.==. If I manually replace all == with Main.== or Prelude.== then it compiles fine.
I don't see why the compiler is having so much difficulty here. x and y are clearly defined as being Int or Char in each case. I've compared what I am doing to the numerous tutorial examples (eg http://www.haskell.org/tutorial/classes.html) and I can't determine why the compiler is being such a jerk in this situation :P
You need to indent the body of your instance definition:
instance Eq Algebra where
Empty == Empty = True
(Nmbr x xl) == (Nmbr y yl) = (x == y) && (xl==yl)
(Smbl x xl) == (Smbl y yl) = (x == y) && (xl==yl)
_ == _ = False
Otherwise the compiler sees it as two things:
An instance Eq Algebra with an empty body, producing the default definitions of a == b = not (a /= b) and vice versa.
A definition of a new infix operator named ==.
Then using == in your code now produces an ambiguity between the == from Eq (defined in Prelude) and the == in your code (Main).
And yes, deriving Eq gives you exactly this kind of structural equality.

Custom Ord instance hangs on lists

import Data.Function (on)
import Data.List (sort)
data Monomial = Monomial
{ m_coeff :: Coefficient
, m_powers :: [(Variable, Power)]
}
deriving ()
instance Ord Monomial where
(>=) = on (>=) m_powers
instance Eq Monomial where
(==) = on (==) m_powers
That's an excerpt from my code, cut down to principal size. Let's try comparing:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
/* Computation hangs here */
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
On a side note, it's interesting that if I replace s/(>=)/(>)/g in instance declaration, it will not hang on the fist pair, but still will on the second:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
True
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
Although the standard states minimal declaration of Eq instance to be either$compare$ or $(>=)$.
What might be the problem here? (>=) on lists seems to work just fine.
Short answer:
You need to provide either (<=) or compare to have a complete definition for Ord, not (>=).
Longer explanation:
It is common for type classes in Haskell to have default implementations of some methods implemented in terms of other methods. You can then choose which ones you want to implement. For example, Eq looks like this:
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
Here, you must either implement (==) or (/=), otherwise trying to use either of them will cause an infinite loop. Which methods you need to provide is usually listed as the minimal complete definition in the documentation.
The minimal complete definition for Ord instances, as listed in the documentation, is either (<=) or compare. Since you've only provided (>=), you have not provided a complete definition, and therefore some of the methods will loop. You can fix it by e.g. changing your instance to provide compare instead.
instance Ord Monomial where
compare = compare `on` m_powers
Let's look at the default instance for Ord:
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
-- NB: must be '<=' not '<' to validate the
-- above claim about the minimal things that
-- can be defined for an instance of Ord:
else if x <= y then LT
else GT
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
-- These two default methods use '<=' rather than 'compare'
-- because the latter is often more expensive
max x y = if x <= y then y else x
min x y = if x <= y then x else y
So, if you supply >= and == as above, only, then you are in trouble, since:
> is defined in terms of compare
But
compare is defined in terms of <=
<= is defined in terms of compare
So you have an infinite loop!
A minimum definition must defined <= or compare, not '>=`.

guard desugaring

I often hear the phrase, guards are just syntactic sugar for if-then-else (or case statements).
Can somebody please desugar the following instance:
halfOf :: Int -> Int
halfOf x | even x = div x 2
(The function is intentionally partial)
Thanks,
halfOf x =
if even x
then div x 2
else error "Incomplete pattern match"
The exact kind of error triggered by an unhandled case is not specified by the language definition, and varies from compiler to compiler.
edit: If there are multiple guards and/or patterns, each guard or pattern match goes into the non-matching part of the previous case.
compare x y
| x == y = foo
| x /= y = bar
compare _ _ = baz
produces
compare x y =
if x == y
then foo
else if x /= y
then bar
else baz
The semantics of pattern matching are defined in the following section of the standard: Formal Semantics of Pattern Matching.
The step that is relevant to your question is c. As you can see, pattern matches with guards of the form
case v of { p | g1 -> e1 ; ...
| gn -> en where { decls }
_ -> e' }
Are translated to pattern matches without guards as:
case e' of
{y ->
case v of {
p -> let { decls } in
if g1 then e1 ... else if gn then en else y ;
_ -> y }}
So pattern guards are defined in terms of if and "fallthrough" is implemented by binding the expression to a variable and then repeating it once in the else clause of the if and then in the pattern that you'd fall through to.
If there is no case to fall through to (as in your example) one will have been inserted by step b, which inserts a default case _ -> error "No match"

Resources