I struggle with creating own instances for my datatypes.
I defined a type like:
data Breakfast = Egg | Sausage Int | Bread Breakfast deriving (Eq, Show)
and want it to be an instance of the class Ord. I want to compare it by some rules like: A Egg is as good as 2 Sausages etc.
I tried it like this:
instance Ord a => Ord (Breakfast) where
compare (Egg) (Sausage 2) = EQ
...
but I get the error:
Variable a occurs more often than in the instance head.
i tried another example and this works fine:
data Down a = Down a deriving (Eq, Show, Read)
instance Ord a => Ord (Down a) where
compare (Down x) (Down y) = y `compare` x
Hope you guys can help me whats wrong. Im very new to Haskell. Thanks
Just remove the constraint on your instance definition:
instance Ord Breakfast where
compare (Egg) (Sausage 2) = EQ
...
You had a constraint on a type variable a which wasn't used on the right-hand side (the instance head).
Related
I'm verifying a c program that uses arrays to store heterogeneous data - in particular, the program uses arrays to implement cons cells, where the first element of the array is an integer value, and the second element is a pointer to the next cons cell.
For example, the free operation for this list would be:
void listfree(void * x) {
if((x == 0)) {
return;
} else {
void * n = *((void **)x + 1);
listfree(n);
free(x);
return;
}
}
Note: Not shown here, but other code sections will read the values of the array and treat it as an integer.
While I understand that the natural way to express this would be as some kind of struct, the program itself is written using an array, and I can't change this.
How should I specify the structure of the memory in VST?
I've defined an lseg predicate as follows:
Fixpoint lseg (x: val) (s: (list val)) (self_card: lseg_card) : mpred := match self_card with
| lseg_card_0 => !!(x = nullval) && !!(s = []) && emp
| lseg_card_1 _alpha_513 =>
EX v : Z,
EX s1 : (list val),
EX nxt : val,
!!(~ (x = nullval)) &&
!!(s = ([(Vint (Int.repr v))] ++ s1)) &&
(data_at Tsh (tarray tint 2) [(Vint (Int.repr v)); nxt] x) *
(lseg nxt s1 _alpha_513)
end.
However, I run into troubles when trying to evaluate void *n = *(void **)x; presumably because the specification states that the memory contains an array of ints not pointers.
The issue is probably as follows, and can almost be solved as follows.
The C semantics permit casting an integer (of the right size) to a pointer, and vice versa, as long as you don't actually do any pointer operations to an integer value, or vice versa. Very likely your C program obeys those rules. But the type system of Verifiable C tries to enforce that local variables (and array elements, etc.) of integer type will never contain pointer values, and vice versa (except the special integer value 0, which is NULL).
However, Verifiable C does support a (proved-foundationally-sound) workaround to this stricter enforcement:
typedef void * int_or_ptr
#ifdef COMPCERT
__attribute((aligned(_Alignof(void*))))
#endif
;
That is: the int_or_ptr type is void*, but with the attribute "align this as void*". So it's semantically identical to void*, but the redundant attribute is a hint to the VST type system to be less restrictive about C type enforcement.
So, when I say "can almost be solved", I'm asking: Can you modify the C program to use an array of "void* aligned as void*" ?
If so, then you can proceed. Your VST verification should use int_or_ptr_type, which is a definition of type Ctypes.type provided by VST-Floyd, when referring to the C-language type of these array elements, or of local variables that these elements are loaded into.
Unfortunately, int_or_ptr_type is not documented in the reference manual (VC.pdf), which is an omission that should be correct. You can look at progs/int_or_ptr.c and progs/verif_int_or_ptr.v, but these do much more than you want or need: They axiomatize operators that distinguish odd integers from aligned pointers, which is undefined in C11 (but consistent with C11, otherwise the ocaml garbage collector could never work). That is, those axiomatized external functions are consistent with CompCert, gcc, clang; but you won't need any of them, because the only operations you're doing on int_or_pointer are the perfectly-legal "comparison with NULL" and "cast to integer" or "cast to struct foo *".
When there are many data types which have almost same structure, how can I implement without almost-duplicated codes?
Here is uncompilable code sample to explain the goal.
{-# LANGUAGE DuplicateRecordFields #-}
class Category a where
method :: a -> String
class ForB b where
...
class ForC c where
...
data A = A {someA :: String, ...}
data B1 = B1 {some :: Int, ...}
data B2 = B2 {some :: Int, ...}
...
data C1 = C1 {some :: Int, ...}
data C2 = C2 {some :: Int, ...}
...
instance Category A where
method (A x) = x
-- Cannot be compiled, but I want to write like this.
instance Category a where
method = show . some
instance ForB B1 where
....
instance ForC C1 where
....
main = do
let a = A "1"
b = B1 2
c = C1 3
print . method $ a
print . method $ b
print . method $ c
I understand that instance does not take type variable a like instance Something a but takes only real data type; Is there no polymorphic instance?
I've tried to solve this by introducing new classes like this, but could not figure it out.
I concerned phantom types or type families, but I could not find any solution.
I do not want to implement almost same code for each data types.
Please refer better explanation and sample to the goal on the background.
Is there any way to short-hand to implement polymorphic(?) instances without reducing data type or Template Haskell (lens,record,extensive package).
Background
I'm preparing series of sample code for transition from OOP to a functional approach.
Here is the simplified base code of the explanation.
And here is little improvement with DuplicateRecordFields.
You can see there are massive instance implements.
(Please do not ask me why do not combine LifeInfo, AnimalInfo and Human in a data type. This is one of the series to solve bunch of problems)
However, to implement Human, Elf, Pine and Rose, I write almost same instances for each. And there are some exceptions for LifeInfo, AnimalInfo, and PlantInfo.
Some points
Do not combine entry data types(A, B, and C) to a data type by using data constructor like data ABC = A {..} | B {..} | C {..}.
But when you can introduce a method for distinguishing each of them by type-checking or implement class-method like things, it will be good.
Please notice that there are classes ForB and ForC.
I'm avoiding Template Haskell and libraries using TH to solve this problem.
I'm working with vr_ad package for e. My question is: What is the difference between 2 following macros for modifying registers (suppose foo register consists of 2 fields: field1 and field2):
1)
write_reg foo {.field1 == 1;};
2)
write_reg_fields foo {.field1 = 1};
I really appreciate any help
There is a very important difference between these forms.
In the first, the register value will be generated, using all defined constraints, + the constraint you wrote in this action (field1 == 1). The new generated value will be written to the DUT.
In the second code, what you state is that you want to modify only one field of the register - field1.
What will happen is that vr_ad will get the current value of the register from the e model (the shadow model), change field1 - and will write the new value the the register in the DUT. None of the other register's fields will be changed. Also - there is no check that the value you assign to field1 complies with the constraints defined on this register.
Lets use it like an example:
foo = 0xA8;
field1 = 0x8;
field2 = 0xA;
will write a totally new value in foo and in RTL, and that value(using your example above where field1 == 1) will be 0x01;
will change only that filed you constrained and value of foo in this case will be 0xA1;
But except that I wanted to say that in fist example you could also get the same result by doing following:
var tem_read_val: uint(bits: 8);
read_reg foo TO tem_read_val;
tem_read_val[3:0] = field1;
write_reg foo read_reg;
=> foo is 0xA1;
From the beginning I was not aware of write reg filds, so I had to use something like this.
I have a wrapper template that looks like this:
#(first: Html, second:Html, third:Html)
<div class="wrapper">
#first
#second
#third
</div>
I have three templates I want to shuffle and place as first, second and third.
Let's name them: views.html.a, views.html.b, views.html.c.
The controller code:
val a = views.html.a
val b = views.html.b
val c = views.html.c
val list = Random.shuffle(List(a, b, c)) // Will use Random.shuffle here but it fails complication either way
Ok(views.html.wrapper(list(0)(), list(1)(), list(2)()))
The complication error:
play.templates.BaseScalaTemplate[play.api.templates.HtmlFormat.Appendable,play.templates.Format[play.api.templates.HtmlFormat.Appendable]] does not take parameters
It appears as entering the object to the List and getting it out tricks the compiler.
If I don't use list and do:
Ok(views.html.wrapper(a(), b(), c()))
it works as expected and renders the page.
I know I can move the random logic to the wrapper template but I prefer to understand / fix the current implementation and learn some Scala in the process.
Thanks
EDIT
After reading serejja's answer, I'll add complexity to the question since this better represents the problem I'm facing.
The three templates need to take a boolean so views.html.a looks like:
#(checkMe:Boolean)
<div ...
So I can't use parentheses before the shuffle. Only after the shuffle occur I wish to send true false true as the booleans.
Using this approach:
Ok(views.html.wrapper(list(0)(true), list(1)(false), list(2)(true)))
gives the following compilation error:
play.templates.BaseScalaTemplate[play.api.templates.Html,play.templates.Format[play.api.templates.Html]] with play.api.templates.Template1[Boolean,play.api.templates.Html] does not take parameters
You were almost there :)
val a = views.html.a()
val b = views.html.b()
val c = views.html.c()
Notice the parentheses. The type of a, b and c now is play.api.templates.HtmlFormat.Appendable instead of the one before.
Now you can pass it as you wanted:
Ok(views.html.wrapper(list(0), list(1), list(2)))
EDIT:
Ok, I cannot imagine what you are up to (so that the solution could be simplified if possible) but I found a workaround.
First, consider that views a, b and c are on the one level of hierarchy:
/ a
BaseScalaTemplate - b
\ c
For this solution to work, these views must have the same number of parameters (a(check: Boolean), b(check: Boolean), c(check: Boolean)) so that they make a List[play.templates.BaseScalaTemplate[play.api.templates.Html,play.templates.Format[play.api.templates.Html]]
with play.api.templates.Template1[Boolean,play.api.templates.Html]] (which means "a generic template with one Boolean parameter").
play.api.templates.Template1 has a method render which takes that parameter and returns you a HtmlFormat.Appendable (which I mentioned earlier).
Considering this your solution might be like this:
val a = views.html.a
val b = views.html.b
val c = views.html.c
val randomizedViews = Random.shuffle(List(a, b, c))
Ok(views.html.wrapper(list(0).render(true), list(1).render(false), list(2).render(true)))
Note that this solution is far from being perfect and I'd suggest you not to use it in real life. I dont think views are intended to be used this way.
I thought I had a firm grasp of Scala's treatment of reference types (i.e., those derived from AnyRef), but now I am not so sure.
If I create a simple class like this
class C(var x: Int = 0) {}
and define a few instances
var a = new C
var b = new C(1)
var c = new C(2)
and then I assign
a = b
I do not get a (shallow) copy, but rather the original reference to the instance to a is lost forever, and a and b are essentially "aliases" for the same object. (This can be seen by looking at the addresses of these items.) This is fine and sensible. It is also clear that these are references (as opposed to values), since I can do
c = null
and this does not generate an error.
Now, suppose I do this
import scala.math.BigInt
var x = BigInt("12345678987654321")
var y = BigInt("98765432123456789")
var z = x + y
This creates three BigInts, with x, y and z, as, I suppose, references to these. In fact, I can do
z = null
and again get no error. However,
y = x
x += 1
does not cause y to change, i.e., it appears that in this case assignment did not simply create another "name" for the object referred to by x, but made a copy of it.
Why does this happen? I cannot find any mechanism (e.g., akin to the "copy constructor" of C++) that would be silently invoked by (what appears to be) straightforward reference assignment.
Any explanation would be greatly appreciated, as two days of web search has proved fruitless.
x += 1 will be expanded into x = x + 1 so it's not only assignment.
If you will look at the source of bigInt you'll see that + creates new instance:
def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
in fact it uses java's BigInteger underneath whose add operations leaves both arguments untouched.
So what basically happens at the end of the day is reference reassignment of result of copy constructor of immutable addition
y = x
x += 1
BigInt is immutable so +1 creates new BigInt that's why y does not change. y still points to previous object while x points to new BigInt object.
I suppose its related to the immutability of BigInt and similar classes, you always get a new immutable object.