I want to count elements in a list that have the same ID
(defrule UniqueIdentifier_testfile
(P (ID_Jess ?id_context) (k $?ass))
?c <- (accumulate (bind ?count 0) ;; initializer
(bind ?count (+ ?count 1)) ;; action
?count ;; result
(and
(P (ID_Jess ?id_as1&:(member$ ?id_as1 ?ass)) (id ?id_ref1))
(P (ID_Jess ?id_as2&:(member$ ?id_as2 ?ass)) (id ?id_ref2))
(and (neq ?id_as1 ?id_as2) (eq ?id_ref1 ?id_ref2))
)
) ;; CE
(test (neq ?c 0))
=>
(printout t "UniqueIdentifier_testfile --> FIRE ! (" ?id_context ":P).id :{"?ass"} -> 'id' not uniques" crlf)
)
As you can see :
a fact of type P has a "real" ID which is reified in the slot "ID_Jess" and an other slot "id" which I'd like to test if it is unique too.
In modelling words :
(deftemplate P
(slot ID_Jess)
(slot id )
(slot m )
(multislot k )
)
It all looks fine, and "compile" allright. But the execution gives me that error :
Jess reported an error in routine HasLHS.addPattern.
Message: Variable used before definition: c.
Program text: ( defrule UniqueIdentifier [...]) at line 70 in file <eval pipe>.
at jess.HasLHS.a(Unknown Source)
...
Anybody got a clue why that ?c is not defined after the accumulate has been executed ?
Even if the condition is never fulfilled, the counter (?count) which is binded as result will at least be a defined '0'.. Am I wrong ?
If I specify an easier conditional element, the accumulate function executes as expected..
Related
Getting clojure.core$count cannot be cast to java.lang.Number error for defined variable count
(defroutes jobs-routes
(context "/jobs" []
(POST "/jobValidation" [name status req] (insert-job jobName jobStatus req)))
In this method I've define a variable count to store the value of total count from the query
(defn insert-job [jobName jobStatus req]
(let [count (db/insert-job {:job-name name :status status})])
(when (> count 0) (println (format "true" )))
(insert-job req) ;
)
Query: db/insert-job
-- :name insert-jobWithValidation :? :*
SELECT count(*) FROM job_history WHERE job_name = :job-name and status = :status
Problem
I want to check that whether If I'm getting out value greater than 0 so I can print something any if count is any positive value then I can perform something new
Your let block has no body, you're closing it right after definitions vector:
(let [count (db/insert-job {:job-name name :status status})])
Note that you are shadowing core function count here.
So when you call this line:
(when (> count 0) (println (format "true" ))), the value of count is count function:
count
=> #object[clojure.core$count 0x69c6a700 "clojure.core$count#69c6a700"]
(> count 0)
Execution error (ClassCastException)
class clojure.core$count cannot be cast to class java.lang.Number
There are some other errors and style inaccuracies:
the names of your variables don't match (jobName jobStatus vs name status)
you're calling (insert-job req) with only one argument, but this function has three
(> ... 0) is pos?
(format "true") is just "true"
Possible fix (maybe you will still have to modify it somehow):
(defn insert-job [job-name job-status req]
(let [my-count (db/insert-job {:job-name job-name :status job-status})]
(if (pos? my-count)
(println "true")
(insert-job job-name job-status req))))
that is probably because of your hugsql query header:
:? :* - returns the rowset, which is not a number.
maybe :? :1 would be more suitable here. Anyway, the query doesn't return a count(*), it rather returns a hash-map (in case of :1) or a list of one hashmap (in case of :*), you would still need to retrieve the value from there.
Something like that (untested):
-- :name insert-jobWithValidation :? :1
SELECT count(*) as amount FROM job_history WHERE job_name = :job-name and status = :status
(defn insert-job [name status req]
(let [res (db/insert-job {:job-name name :status status})]
(when (-> res :amount pos?)
(println true))
(insert-job req)))
UPD: omg, let with no body, indeed, #Martin Půda, thanks )
i would say, what you want is something like that:
-- :name count-jobs-by-name-and-status :? :1
SELECT count(*) as amount FROM job_history WHERE job_name = :job-name and status = :status
(defn insert-job-if-not-exists [name status req]
(if (->> {:job-name name :status status}
db/count-jobs-by-name-and-status
:amount
pos?)
(println "job already exists")
(insert-job req)))
new to jess. i have a problem i'm using as a learning tool. it is the process to
assign available docks in our marina. the process works like this, a dock becomes
available, it is compared against a list of requests. if there is a match, one
or more, then a series of rules are triggered to award the dock to the winning
request.
i've written a short program (see below) to start that process. when i execute
it i get the following error message:
Jess, the Rule Engine for the Java Platform
Copyright (C) 2008 Sandia Corporation
Jess Version 7.1p2 11/5/2008
Jess reported an error in routine call
while executing (call ?it hasNext)
while executing (while (call ?it hasNext) (bind ?token (call ?it next))
(bind ?fact (call ?token ?fact 1)) (bind ?person (fact-slot-value ?fact name))
(printout t ?person crlf)).
Message: No method named 'hasNext' found in class jess.QueryResult.
Program text: ( while ( ?it hasNext ) ( bind ?token ( call ?it next ) )
( bind ?fact ( call ?token ?fact 1 ) ) ( bind ?person
( fact-slot-value ?fact name ) ) ( printout t ?person crlf ) )
at line 32 in file
C:\data\code\eclipseJessTutor\JessTutor\src\com\soundsoftware\jesstutor\defquery.clp.
(defglobal ?*curSlip* = nil)
(deftemplate bid
(slot person)
(slot slipRequestedID)
(slot boatID))
(deftemplate slip
(slot slipID)
(slot slength)
(slot swidth)
(slot sdepth))
(deftemplate person
(slot name)
(slot bycseniority)
(slot boatID)
(slot currentSlip))
(deffacts bids
(bid (person John) (slipRequestedID A13) (boatID GEM))
(bid (person Joe) (slipRequestedID A13) (boatID FarNiente))
(bid (person Frank) (slipRequestedID B9) (boatID DoryO)))
(deffacts freeSlips
(slip (slipID A13)))
(defquery bidLookup
(declare (variables ?slipID))
(bid (slipRequestedID ?sID & :( = ?slipID))))
(bind ?collOfBids (run-query* bidLookup A13))
<External-Address: java.util.AbstractList$Itr>
(while (?collOfBids hasNext)
(bind ?token (call ?collOfBids next))
(bind ?fact (call ?token ?fact 1))
(bind ?person (fact-slot-value ?fact name))
(printout t ?person crlf)
)
any help is appreciated,
duetto
I want to using call/cc to simulating the exception handling statement: try...(throw)...exception. Here's the code:
(define (month n) ; check if it's a month number (1-12)
(if (or (not (integer? n)) (< n 1) (> n 12))
(throw -1)
(display n)
)
)
(define error (call/cc
(lambda(throw)
(begin
(month 12)
(month -1)
(throw -1) ; won't be executed
(month 10)
(display "Hello world")
)
)
)
)
(if error
(display Error occured!")
)
However, When I executed it, it showed the error (in biwascheme):
Error: execute: unbound symbol: "throw" [(anon), month]
I think that the throw in lambda is not the same as the throw in the called function "month", However, how can I solve it? Is it can be solved with making marco with some keywords? eg:
(define-syntax exception-handling
(syntax-rules (throw raise error)
((_ body catch)
(define (error
(call/cc (lambda (throw) (begin body))))
)
(if error (begin catch)))
)
)
In Scheme, continuations are first-class. A captured continuation is just another value. Pass it in to your month function as another argument:
(define (month n throw) ; check if it's a month number (1-12)
(if (or (not (integer? n)) (< n 1) (> n 12))
(throw -1)
(display n)))
And call it as
....
(month 12 throw)
....
(month 10 throw)
....
Your indentation style is not conducive to the readability of your code.
Here is an example of how to use call-with-current-continuation to make a "throw".
#lang r5rs
(define (month n) ; check if it's a month number (1-12)
(call-with-current-continuation
(lambda (throw)
(define ok (and (integer? n) (<= 1 n 12)))
(if (not ok)
(throw "the month number must be between 1 and 12"))
(display n)
(newline))))
(month 12)
(month -1)
(month 10)
(display "Hello world\n")
I've find the way to simulating try and exception-handling:
(define-syntax try
(syntax-rules (catch)
((_ body catch handling)
(let ()
; evaluating body and save it as an exception.
(define except (begin body))
(if (and
(pair? except)
(eq? (car except) 'exception))
(handling except)
)
)
)
)
)
; returns an exception '(exception, "Error messenge")
(define (exception-content msg throw)
(throw (cons 'exception msg)))
; throw an exception if n = 0
(define (reciprocal n throw)
(if (= n 0)
(exception-content "Div 0 error" throw)
(/ 1 n)
)
)
; f1(n) = reciprocal(n) + 1
(define (f1 n throw)
(+ (reciprocal n throw) 1)
)
; main program
(try ; with call/cc and the continuation variable "throw"
(call-with-current-continuation
(lambda (throw)
(display (f1 2 throw))
(newline)
(display (f1 0 throw))
; the following won't be executed
(newline)
(display (f1 1 throw))
)
)
catch
; exception handling
(lambda (exception)
(display (cdr exception))
)
)
The printed result is:
3/2
Div 0 error
Im pretty much new to Haskell, so if Im missing key concept, please point it out.
Lets say we have these two functions:
fact n
| n == 0 = 1
| n > 0 = n * (fact (n - 1))
The polymorphic type for fact is (Eq t, Num t) => t -> t Because n is used in the if condition and n must be of valid type to do the == check. Therefor t must be a Number and t can be of any type within class constraint Eq t
fib n
| n == 1 = 1
| n == 2 = 1
| n > 2 = fib (n - 1) + fib (n - 2)
Then why is the polymorphic type of fib is (Eq a, Num a, Num t) => a -> t?
I don't understand, please help.
Haskell always aims to derive the most generic type signature.
Now for fact, we know that the type of the output, should be the same as the type of the input:
fact n | n == 0 = 1
| n > 0 = n * (fact (n - 1))
This is due to the last line. We use n * (fact (n-1)). So we use a multiplication (*) :: a -> a -> a. Multiplication thus takes two members of the same type and returns a member of that type. Since we multiply with n, and n is input, the output is of the same type as the input. Since we use n == 0, we know that (==) :: Eq a => a -> a -> Bool so that means that that input type should have Eq a =>, and furthermore 0 :: Num a => a. So the resulting type is fact :: (Num a, Eq a) => a -> a.
Now for fib, we see:
fib n | n == 1 = 1
| n == 2 = 1
| n > 2 = fib (n - 1) + fib (n - 2)
Now we know that for n, the type constraints are again Eq a, Num a, since we use n == 1, and (==) :: Eq a => a -> a -> Bool and 1 :: Num a => a. But the input n is never directly used in the output. Indeed, the last line has fib (n-1) + fib (n-2), but here we use n-1 and n-2 as input of a new call. So that means we can safely asume that the input type and the output type act independently. The output type, still has a type constraint: Num t: this is since we return 1 for the first two cases, and 1 :: Num t => t, and we also return the addition of two outputs: fib (n-1) + fib (n-2), so again (+) :: Num t => t -> t -> t.
The difference is that in fact, you use the argument directly in an arithmetic expression which makes up the final result:
fact n | ... = n * ...
IOW, if you write out the expanded arithmetic expression, n appears in it:
fact 3 ≡ n * (n-1) * (n-2) * 1
This fixes that the argument must have the same type as the result, because
(*) :: Num n => n -> n -> n
Not so in fib: here the actual result is only composed of literals and of sub-results. IOW, the expanded expression looks like
fib 3 ≡ (1 + 1) + 1
No n in here, so no unification between argument and result required.
Of course, in both cases you also used n to decide how this arithmetic expression looks, but for that you've just used equality comparisons with literals, whose type is not connected to the final result.
Note that you can also give fib a type-preservig signature: (Eq a, Num a, Num t) => a -> t is strictly more general than (Eq t, Num t) => t -> t. Conversely, you can make a fact that doesn't require input- and output to be the same type, by following it with a conversion function:
fact' :: (Eq a, Integral a, Num t) => a -> t
fact' = fromIntegral . fact
This doesn't make a lot of sense though, because Integer is pretty much the only type that can reliably be used in fact, but to achieve that in the above version you need to start out with Integer. Hence if anything, you should do the following:
fact'' :: (Eq t, Integral a, Num t) => a -> t
fact'' = fact . fromIntegral
This can then be used also as Int -> Integer, which is somewhat sensible.
I'd recommend to just keep the signature (Eq t, Num t) => t -> t though, and only add conversion operations where it's actually needed. Or really, what I'd recommend is to not use fact at all – this is a very expensive function that's hardly ever really useful in practice; most applications that naïvely end up with a factorial really just need something like binomial coefficients, and those can be implemented more efficiently without a factorial.
Is it possible to define a single notation for multiple constructors in Coq? If the constructors differ by their argument types, they might be inferrable from them. A minimal (non-)working example:
Inductive A : Set := a | b | c: C -> A | d: D -> A
with C: Set := c1 | c2
with D: Set := d1 | d2.
Notation "' x" := (_ x) (at level 19).
Check 'c1. (*?6 c1 : ?8*)
In this case, constructor inference doesn't work. Maybe there's another way to specify a constructor as a variable?
You can create a typeclass with the constructors as instances and let the instance resolution mechanism infer the constructor to call for you:
Class A_const (X:Type) : Type :=
a_const : X -> A.
Instance A_const_c : A_const C := c.
Instance A_const_d : A_const D := d.
Check a_const c1.
Check a_const d2.
By the way, with Coq 8.5, if you really want a notation ' x to result in the exact constructor applied to x, rather than e.g. #a_const C A_const_c c1, then you can use ltac-terms to accomplish that:
Notation "' x" := ltac:(match constr:(a_const x) with
| #a_const _ ?f _ =>
let unfolded := (eval unfold f in f) in
exact (unfolded x)
end) (at level 0).
Check 'c1. (* c c1 : A *)
Check 'd2. (* d d2 : A *)
In fact, the idea of using an ltac-term leads to an entirely different solution from the other one I posted:
Notation "' x" := ltac:(let T := (type of x) in
let T' := (eval hnf in T) in
match T' with
| C => exact (c x)
| D => exact (d x)
end) (at level 0).
Check 'c1. (* c c1 : A *)
Check 'd2. (* d d2 : A *)
(Here the eval hnf part lets it work even if the type of the argument isn't syntactically equal to C or D, but it does reduce to one of them.)
Apparently, it's easy:
Notation "' x" := ((_:_->A) x) (at level 19).
Check 'c1. (*' c1 : A*)