Difficulties with solving the exercises in the K Framework Tutorial - kframework

Tutorial 1 Lesson 8 ( mu-defined )
My attempt is to substitute the existing rule : "rule mu X . E => E[(mu X . E) / X]"
with the rule :
rule mu X:KVar . E:Exp
=> let X =
(lambda $x . (( lambda X . E) (lambda $y . ($x $x $y))))
(lambda $x . (( lambda X . E) (lambda $y . ($x $x $y)))) [macro]"
Unfortanetely it wont compile. What am i doing wrong ? Is this solution correct ?
Tutorial 1 Lesson 8 ( SK-combinators )
They have this part in the README of the exercise:
" For example, lambda x . if x then y else z cannot be transformed into combinators as is,
but it can if we assume a builtin conditional function constant, say cond,
and desugar if_then_else_ to it. Then this expression becomes
lambda x . (((cond x) y) z), which we know how to transform. "
My struggle is with ' say cond, and desugar if_then_else_ to it. '
How do i do this part ? Any help would be appreciated.
Tutorial 2 Lesson 4 (purely-syntactic)
They have this part in the README of the exercise:
'Hint: make sequential composition strict(1) or seqstrict, and have
statements reduce to {} instead of .; and don't forget to make
{} a KResult (you may need a new syntactic category for that, which
only includes {} and is included in KResult).'
My struggle is with the part: ' and have
statements reduce to {} instead of .; and don't forget to make
{} a KResult (you may need a new syntactic category for that, which
only includes {} and is included in KResult)'
How do i do this ? Any hints ?
Tutorial 2 Lesson 4 (uninitialized-variables)
I have created the following module:
module UNDEFINED
rule <k> int (X,Xs => Xs);_ </k> <state> Rho:Map (.Map => X|->"##") </state>
requires notBool (X in keys(Rho))
endmodule
But this initializes variables with "##". How do i initialize a variable with "undefined" ? Any hints ?
Tutorial 3 Lesson 1 (callCC)
For this exercise i created a very similar code similar to the callcc:
syntax Exp ::= "callCC" Exp [strict]
syntax Val ::= cc(K)
rule <k> (callCC V:Val => V cc(K)) ~> _ </k>
rule <k> cc(K) V ~> _ => V ~> _ </k>
For some reason it wont compile . What am i doing wrong ? Is this solution correct ?

Related

How to check if there exist a sub list of a list in a Map?

I am stuck in the implementation of a function and also I am not sure if it is the correct way to solve my problem.
Description of my problem
For the context, I want to be able to borrow (a unary operation) a field of a structure only if no references on this field or its parent already exist. Let me clarify my this with the following example. I hope things will become more clear with code.
struct p{ x, p2:{ x, p3: {x} }
let a = ref p
let b = ref p.p2
let c = ref p.p2.p3
Here I have a structure p with nested fields and 3 references: one on p and 2 on its fields.
I use a Map to store the mapping between referred and their ref:
<env>
1 |-> 0 // 1 is a and 0 is p
2 |-> 0.1 // 2 is b and 0.1 is p.p2
3 |-> 0.1.2 // 3 is c and 0.1.2 is p.p2.p3
</env>
So now, If I want to do the unary operator borrow on p.p2.p3.x:
borrow p.p2.p3.x;
This operation should fail because a,b and c exists in my env.
My code
So, I tried to implement this in this snippet:
module TEST-SYNTAX
import DOMAINS
syntax Ref ::= "ref" "{" Path "}"
syntax Path ::= List{Int,","}
syntax Stmts ::= List{Stmt, ";"}
syntax Stmt ::= Ref
| Int "borrow" "{" Path "}"
endmodule
module TEST
import TEST-SYNTAX
configuration <T>
<k>$PGM:Stmts</k>
<env> .Map </env>
</T>
rule S:Stmt ; Ss:Stmts => S ~> Ss
rule .Stmts => .
rule <k> ref { P:Path } => . ... </k>
<env> Rho:Map => Rho[!I:Int <- P] </env>
syntax Bool::= #checkborrow(Int, List, Path) [function]
syntax List ::= #pathToSubPaths(Path, List) [function]
rule <k> N:Int borrow { P:Path } => #checkborrow(N, #pathToSubPaths(P, .List), P) ... </k>
rule #pathToSubPaths(.Path, S:List) => S
endmodule
I am stuck on how I can implement the #checkborrow function. My idea is to first generate all the sub path of a given paths, for example:
#pathToSubPath(p.p2.p3.x) => { {p} , { p.p2 }, { p.p2.p3 }, { p.p2.p3.x } }
After, make a projection function on env to see if the element exist or not:
#refForSubPathsExist(SubPaths:Set) => {True, True, True, False}
Then reducing this returned Set with a folding OR
#checkborrow({True, True, True, False}) => True
For now, I am stuck in the implementation of #pathToSubPath.
Thank you if you had the courage to read the whole question :). I am unfamiliar with K, so I am looking for help.
NOTE:
We are using this version of K Framework: https://github.com/kframework/k/releases/tag/nightly-f5ea5c7

Can I delete an element of SetHash and use its value in Perl 6?

I would like to delete any element of a SetHash, so that its value be returned:
my SetHash $a;
$a<m n k> = 1..*;
my $elem = $a.mymethod;
say $elem; # n
say $a; # SetHash(m k)
I can do it in two steps as follows. Is there a better way?
my $elem = $a.pick;
$a{$elem}--;
And by the way, is there a more idiomatic way of adding several elements to a SetHash?
Is the following any better?
my SetHash $a;
$a{$_}++ for <m n k>;
or
my SetHash $a;
$a<m n k> X= True;
Since you want to remove any random element from the set and return the value you got, I'd recommend using the grab method on Setty things (only works properly on mutable sets like SetHash): https://docs.perl6.org/type/SetHash#(Setty)_method_grab
Depending on what exact return value you need, maybe grabpairs is better.
UPD I'm leaving this answer up for now rather than deleting it, but see timotimo's answer.
I would like to delete an element of a SetHash, so that its value be returned
Use the :delete adverb.
Per the Subscript doc page,
the :delete adverb will delete the element(s) from the collection or, if supported by the collection, create a hole at the given index(es), in addition to returning their value(s):
my %associative = << :a :b :c >> ;
my $deleted = %associative<< a c >> :delete ;
say $deleted ; # (True True)
say %associative ; # {b => True}
UPD Integrating #piojo's and #EugeneBarsky's comments and answers:
my %associative = << :a :b :c >> ;
my $deleted = .{.keys.pick } :delete :k with %associative ;
say $deleted ; # b
say %associative ; # {a => True, c => True}
is there a more idiomatic way of adding several elements to a SetHash?
Plain assignment with a list on the right hand side works, e.g.
$a<m n k> = True, True, True;
$a<m n k> = True xx *;
$a<m n k> = True ... *;
I've used and seen others using both the formulations in your examples too.
If I understand your comments correctly, you want to delete an element from a hash without knowing whether it exists, and get the element as a return value if it does exist. This can be done by combining the :delete and :k adverbs.
my %set := SetHash.new: ('a'..'g');
my #removed = %set<a e i o u>:delete :k;
say #removed; # output: [a e]
Another approach to deleting the element and returning it, is to augment the SetHash class with a custom method:
use v6;
use MONKEY-TYPING;
augment class SetHash {
method delete-elem(Any $elem) {
self.DELETE-KEY( $elem );
return $elem;
}
}
my SetHash $a = <m n k>.SetHash;
$a<a b c>»++; # add some more elements to the SetHash...
my $elem = $a.delete-elem( $a.pick );
say "Deleted: $elem";
say $a;
Output:
Deleted: m
SetHash(a b c k n)
Using a combination of the answers, it seems I've managed to do what I wanted:
my SetHash $s;
$s = <a b c d e f>.SetHash;
my $deleted = $s{ $s.pick } :delete :k;
say $deleted; # f
say $s; # SetHash(a b c d e)

Can I write a generic function-wrapping function for a Wrapper interface representing a type that wraps some other type?

The full code example below (which successfully compiles) is a simplified and slightly contrived example of my problem.
NatPair is a pair of Nats, and I want to "lift" the binaryNum operations to NatPair pointwise, using the function lift_binary_op_to_pair.
But I can't implement Num NatPair because NatPair is not a data constructor.
So, I wrap it in a type WrappedNatPair, and I can provide a Num implementation for that type, with corresponding 'lifted' versions of + and *.
Then I want to generalise the idea of a wrapper type, with my Wrapper interface.
The function lift_natpair_bin_op_to_wrapped can lift a binary operation from NatPair
to WrappedNatPair, and the implementation code is entirely in terms of the unwrap and
wrap Wrapper interface methods.
But, if I try to generalise to
lift_bin_op_to_wrapped : Wrapper t => BinaryOp WrappedType -> BinaryOp t
then the type signature won't even compile, with error:
`-- Wrapping.idr line 72 col 23:
When checking type of Main.lift_bin_op_to_wrapped:
Can't find implementation for Wrapper t
(where the error location is the location of ':' in the type signature).
I think the problem is that t doesn't appear anywhere in the
type signature for the Wrapper interface WrapperType method,
so WrapperType can't be invoked anywhere other than inside
the interface definition itself.
(The workaround is to write boilerplate lift_<wrapped>_bin_op_to_<wrapper> methods with the same implementation code op x y = wrap $ op (unwrap x) (unwrap y) each time, which is not intolerable. But I would like to have a clear understanding of why I can't write the generic lift_bin_op_to_wrapped method.)
The full code which successfully compiles:
%default total
PairedType : (t : Type) -> Type
PairedType t = (t, t)
NatPair : Type
NatPair = PairedType Nat
data WrappedNatPair : Type where
MkWrappedNatPair : NatPair -> WrappedNatPair
equal_pair : t -> PairedType t
equal_pair x = (x, x)
BinaryOp : Type -> Type
BinaryOp t = t -> t -> t
lift_binary_op_to_pair : BinaryOp t -> BinaryOp (PairedType t)
lift_binary_op_to_pair op (x1, x2) (y1, y2) = (op x1 y1, op x2 y2)
interface Wrapper t where
WrappedType : Type
wrap : WrappedType -> t
unwrap : t -> WrappedType
Wrapper WrappedNatPair where
WrappedType = NatPair
wrap x = MkWrappedNatPair x
unwrap (MkWrappedNatPair x) = x
lift_natpair_bin_op_to_wrapped : BinaryOp NatPair -> BinaryOp WrappedNatPair
lift_natpair_bin_op_to_wrapped op x y = wrap $ op (unwrap x) (unwrap y)
Num WrappedNatPair where
(+) = lift_natpair_bin_op_to_wrapped (lift_binary_op_to_pair (+))
(*) = lift_natpair_bin_op_to_wrapped (lift_binary_op_to_pair (*))
fromInteger x = wrap $ equal_pair (fromInteger x)
WrappedNatPair_example : the WrappedNatPair 8 = (the WrappedNatPair 2) + (the WrappedNatPair 6)
WrappedNatPair_example = Refl
(Platform: Ubuntu 16.04 running Idris 1.1.1-git:83b1bed.)
I think the problem is that t doesn't appear anywhere in the type signature for the Wrapper interface WrapperType method, so WrapperType can't be invoked anywhere other than inside the interface definition itself.
You're right here. This is why you receive this error. You can fix this compilation error by explicitly specifying which types is wrapper like this:
lift_bin_op_to_wrapped : Wrapper w => BinaryOp (WrappedType {t=w}) -> BinaryOp w
lift_bin_op_to_wrapped {w} op x y = ?hole
But this probably won't help you because Idris somehow cannot deduce correspondence between w and WrappedType. I would love to see explanation of this fact. Basically compiler (I'm using Idris 1.0) says me next things:
- + Wrap.hole [P]
`-- w : Type
x : w
y : w
constraint : Wrapper w
op : BinaryOp WrappedType
-----------------------------------
Wrap.hole : w
Your WrappedType dependently typed interface method implements pattern matching on types in some tricky way. I think this might be a reason why you have problems. If you're familiar with Haskell you might see some similarities between your WrappedType and -XTypeFamilies. See this question:
Pattern matching on Type in Idris
Though you still can implement general wrapper function. You only need to desing your interface differently. I'm using trick described in this question: Constraining a function argument in an interface
interface Wraps (from : Type) (to : Type) | to where
wrap : from -> to
unwrap : to -> from
Wraps NatPair WrappedNatPair where
wrap = MkWrappedNatPair
unwrap (MkWrappedNatPair x) = x
lift_bin_op_to_wrapped : Wraps from to => BinaryOp from -> BinaryOp to
lift_bin_op_to_wrapped op x y = wrap $ op (unwrap x) (unwrap y)
Num WrappedNatPair where
(+) = lift_bin_op_to_wrapped (lift_binary_op_to_pair {t=Nat} (+))
(*) = lift_bin_op_to_wrapped (lift_binary_op_to_pair {t=Nat}(*))
fromInteger = wrap . equal_pair {t=Nat} . fromInteger
This compiles and works perfectly.

Is there a more convenient way to use nested records?

As I told before, I'm working in a library about algebra, matrices and category theory. I have decomposed the algebraic structures in a "tower" of record types, each one representing an algebraic structure. As example, to specify a monoid, we define first a semigroup and to define a commutative monoid we use monoid definition, following the same pattern as Agda standard library.
My trouble is that when I need a property of an algebraic structure that is deep within another one (e.g. property of a Monoid that is part of a CommutativeSemiring) we need to use a number of a projections equal to desired algebraic structure depth.
As an example of my problem, consider the following "lemma":
open import Algebra
open import Algebra.Structures
open import Data.Vec
open import Relation.Binary.PropositionalEquality
open import Algebra.FunctionProperties
open import Data.Product
module _ {Carrier : Set} {_+_ _*_ : Op₂ Carrier} {0# 1# : Carrier} (ICSR : IsCommutativeSemiring _≡_ _+_ _*_ 0# 1#) where
csr : CommutativeSemiring _ _
csr = record{ isCommutativeSemiring = ICSR }
zipWith-replicate-0# : ∀ {n}(xs : Vec Carrier n) → zipWith _+_ (replicate 0#) xs ≡ xs
zipWith-replicate-0# [] = refl
zipWith-replicate-0# (x ∷ xs) = cong₂ _∷_ (proj₁ (IsMonoid.identity (IsCommutativeMonoid.isMonoid
(IsCommutativeSemiring.+-isCommutativeMonoid
(CommutativeSemiring.isCommutativeSemiring csr)))) x)
(zipWith-replicate-0# xs)
Note that in order to access the left identity property of a monoid, I need to project it from the monoid that is within the commutative monoid that lies in the structure of an commutative semiring.
My concern is that, as I add more and more algebraic structures, such lemmas it will become unreadable.
My question is: Is there a pattern or trick that can avoid this "ladder" of record projections?
Any clue on this is highly welcome.
If you look at the Agda standard library, you'll see that for most specialized algebraic structures, the record defining them has the less specialized structure open public. E.g. in Algebra.AbelianGroup, we have:
record AbelianGroup c ℓ : Set (suc (c ⊔ ℓ)) where
-- ... snip ...
open IsAbelianGroup isAbelianGroup public
group : Group _ _
group = record { isGroup = isGroup }
open Group group public using (setoid; semigroup; monoid; rawMonoid)
-- ... snip ...
So an AbelianGroup record will have not just the AbelianGroup/IsAbelianGroup fields available, but also setoid, semigroup and monoid and rawMonoid from Group. In turn, setoid, monoid and rawMonoid in Group come from similarly open public-reexporting these fields from Monoid.
Similarly, for algebraic property witnesses, they re-export the less specialized version's fields, e.g. in IsAbelianGroup we have
record IsAbelianGroup
{a ℓ} {A : Set a} (≈ : Rel A ℓ)
(∙ : Op₂ A) (ε : A) (⁻¹ : Op₁ A) : Set (a ⊔ ℓ) where
-- ... snip ...
open IsGroup isGroup public
-- ... snip ...
and then IsGroup reexports IsMonoid, IsMonoid reexports IsSemigroup, and so on. And so, if you have IsAbelianGroup open, you can still use assoc (coming from IsSemigroup) without having to write out the whole path to it by hand.
The bottom line is you can write your function as follows:
open CommutativeSemiring CSR hiding (refl)
open import Function using (_⟨_⟩_)
zipWith-replicate-0# : ∀ {n}(xs : Vec Carrier n) → zipWith _+_ (replicate 0#) xs ≡ xs
zipWith-replicate-0# [] = refl
zipWith-replicate-0# (x ∷ xs) = proj₁ +-identity x ⟨ cong₂ _∷_ ⟩ zipWith-replicate-0# xs

Global variables in Haskell

I have this function:
map(\x -> l ++ [x]) "Show" where l = ""
I want the values of l to be saved at every step of the map function (e.g. I don't want to return ["S","h","o","w"], I want it to return ["S","Sh","Sho","Show"])
Can someone help me?
You're nearly there:
inits (x:xs) = map (\ys -> x:ys) ([]:inits xs)
inits [] = []
but note that you can rewrite (\ys -> x:ys) as (x:), which puts x at the front of each list it encounters, giving
inits (x:xs) = map (x:) ([]:inits xs)
inits [] = []
This works because map (x:) ([]:inits xs) gives you (x:[]) : map (x:) (inits xs), so everything in the list starts with x, and the first one is just [x]. That's true also of inits xs, so each gets one element longer.
There's a standard function
As usual, you're not the first to want this, which is why the function is defined already in Data.List. All you need to do is add
import Data.List
to the top of the program and you get inits predefined.
How is inits defined there?
Now if you look up hoogle for that, http://www.haskell.org/hoogle/?q=inits you can click through to find
inits :: [a] -> [[a]]
inits xs = [] : case xs of
[] -> []
x : xs' -> map (x :) (inits xs')
which is almost exactly the same idea, but in a case statement, which moves the pattern matching to be internal to the function.
Notice that this is slightly different to what you wanted, because you get a [] at the front of your answer, but you could use tail to get rid of that.
myinits = tail.inits
How can you find if there's already a function?
You wanted to turn a list into a list of lists. That should have type [a]->[[a]]. You can search for that on hoogle http://www.haskell.org/hoogle/?hoogle=[a]+-%3E+[[a]] and it's the top answer (more generally it might be lower down and you'd have to browse a bit.
This works for a lot of standard functions, since hoogle indexes all of base for a start.
Use scanl :
Prelude> scanl (\a c -> a++[c]) "" "Show"
["","S","Sh","Sho","Show"]
An efficient version:
Prelude> map reverse . scanl (flip (:)) [] $ "Show"
["","S","Sh","Sho","Show"]
Use Data.List.inits:
> tail $ inits "Show"
["S","Sh","Sho","Show"]
Just combine inits and tail functions from Prelude:
tail . inits $ "Show"