Inserting a copy of a tuple into a list - list

I'm still new to Haskell, my problem is I have issues with adding a modified copy of data type instance into the list of those instances (don't know if it's not synonym).
Data type name is Task, short Tas.
If a task is fulfilled I need to mark it as fulfilled and if it's repeatable, I need to set next date for it (while keeping it in fulfilled tasks).
My approach is to create a copy of that task, basing on it, but with different ID and date and insert it into the list.
remakeDate serves for returning increased date of Task.
fulfilledTaskInList :: [Task] -> Int -> Int -> [Task]
fulfilledTaskInList [ ] check_ID pk_task = []
fulfilledTaskInList (x:xs) check_ID pk_task = if getId x == check_ID then
if getRepeatT x /= 0 then let help = remakeTask x pk_task in
(setFulfill x):help:xs
else (setFulfill x):xs
else x: fulfilledTaskInList xs check_ID pk_task
remakeTask x pk_task = do
(in_year, in_month, in_day) <- remakeDate (getYear x) (getMonth x) (getDay x) (getRepeatT x)
(Tas {id_Task = pk_task , name = showName x , descr = showDescr x, day = in_day, month = in_month, year = in_year, hour = getHour x, minute = getMinute x, fulfill = 0, repeatT = getRepeatT x})
Error thrown by ghci:
Task.hs:94:18:
Couldn't match expected type `IO b0' with actual type `Task'
In a stmt of a 'do' block:
(Tas
{id_Task = pk_task, name = showName x, descr = showDescr x,
day = in_day, month = in_month, year = in_year, hour = getHour x,
minute = getMinute x, fulfill = 0, repeatT = getRepeatT x})
In the expression:
do { (in_year, in_month, in_day) <- remakeDate
(getYear x) (getMonth x) (getDay x)
(getRepeatT x);
(Tas
{id_Task = pk_task, name = showName x, descr = showDescr x,
day = in_day, month = in_month, year = in_year, hour = getHour x,
minute = getMinute x, fulfill = 0, repeatT = getRepeatT x}) }
In an equation for `remakeTask':
remakeTask x pk_task
= do { (in_year, in_month, in_day) <- remakeDate
(getYear x)
(getMonth x)
(getDay x)
(getRepeatT x);
(Tas
{id_Task = pk_task, name = showName x, descr = showDescr x,
day = in_day, month = in_month, year = in_year, hour = getH
our x,
minute = getMinute x, fulfill = 0, repeatT = getRepeatT x})
}
Failed, modules loaded: Functions.

The error is saying that the do block in remakeTask is producing a Task as its last statement, but because it's a do block, it should produce a monadic value, in this case IO something.
You can add a return similar to the one in plusYear to fix this specific problem. However in general you seem to be using IO when you don't really need to, so you might instead investigate removing the do blocks along with the use of return and IO.

Related

Is there an alternative to UNION that does fewer scans?

See the db-fiddle.
On the following table
CREATE TABLE foo (x INTEGER PRIMARY KEY, y INTEGER);
INSERT INTO foo VALUES (0,41), (1, 23), (2,45), (3,32), ...
I need the x and y which has min(y) over groups of 10 x, and the same for max(y):
SELECT x, min(y) FROM foo GROUP BY (x/10)
UNION
SELECT x, max(y) FROM foo GROUP BY (x/10);
The EXPLAIN QUERY PLAN output shows that two scans of the table are performed
`--COMPOUND QUERY
|--LEFT-MOST SUBQUERY
| |--SCAN TABLE foo
| `--USE TEMP B-TREE FOR GROUP BY
`--UNION ALL
|--SCAN TABLE foo
`--USE TEMP B-TREE FOR GROUP BY
Is there any way to reword the query so that only one scan is performed?
What I've done in the mean time is to select all rows (SELECT x, y FROM foo;) and manually aggregate min/max as rows are returned to the host language:
int lastGroup = 0;
while (sqlite3_step(query) == SQLITE_ROW) {
int x = sqlite3_column_int(query, 0);
int y = sqlite3_column_int(query, 1);
int group = x / 10;
if (group != lastGroup) {
// save minX, minY, maxX, maxY in a list somewhere
// reset minX, minY, maxX, maxY
// ...
lastGroup = group;
}
else {
if (y < minY) {
minX = x;
minY = y;
}
else if (y > maxY) {
maxX = x;
maxY = y;
}
}
}
This achieves a single scan and the whole process is more than twice as fast... but I'd rather express this logic declaritively in SQL if possible.
Why not just do one group by with more columns?
On the following table
SELECT (x/10) * 10, min(y), max(y)
FROM foo
GROUP BY (x/10)
If you want multiple rows, you can unpivot afterwards:
SELECT x, (CASE WHEN x.which = 1 THEN min_y ELSE max_y END) as min_max_y
FROM (SELECT (x/10) * 10 as x, min(y) as min_y, max(y) as max_y
FROM foo
GROUP BY (x/10)
) f CROSS JOIN
(SELECT 1 as which UNION ALL SELECT 2) x;
EDIT:
You are using a SQLite extension -- which is not consistent with the standard or any other SQL language. A better way to write this uses window functions:
select x, y
from (select f.*,
row_number() over (partition by (x/10) order by y asc) as seqnum_asc,
row_number() over (partition by (x/10) order by y desc) as seqnum_desc
from foo f
) f
where 1 in (seqnum_asc, seqnum_desc);
Or, using first_value() if you don't like subqueries:
select distinct (x/10)*10, -- this is not necessary but helps to make the purpose clear
first_value(x) over (partition by (x/10) order by y asc) as x_at_min_y,
min(y) over (partition by x/10) as min_y,
first_value(x) over (partition by (x/10) order by y desc) as x_at_max_y,
max(y) over (partition by x/10) as max_y
from foo;
Here is a db-fiddle.
If you like, you can unpivot afterwards, as illustrated above.

Printing Lists in Haskell new

Brand new to haskell and I need to print out the data contained on a seperate row for each individual item
Unsure on how to
type ItemDescr = String
type ItemYear = Int
type ItemPrice = Int
type ItemSold = Int
type ItemSales = Int
type Item = (ItemRegion,ItemDescr,ItemYear,ItemPrice,ItemSold,ItemSales)
type ListItems = [Item]
rownumber x
| x == 1 = ("Scotland","Desktop",2017,900,25,22500)
| x == 2 = ("England","Laptop",2017,1100,75,82500)
| x == 3 = ("Wales","Printer",2017,120,15,1800)
| x == 4 = ("England","Printer",2017,120,60,7200)
| x == 5 = ("England","Desktop",2017,900,50,45000)
| x == 6 = ("Wales","Desktop",2017,900,20,18000)
| x == 7 = ("Scotland","Printer",2017,25,25,3000)
showall
--print??
So for example on each individual line
show
"Scotland","Desktop",2017,900,25,22500
followed by the next record
Tip 1:
Store the data like this
items = [("Scotland","Desktop",2017,900,25,22500),
("England","Laptop",2017,1100,75,82500),
("Wales","Printer",2017,120,15,1800),
("England","Printer",2017,120,60,7200),
("England","Desktop",2017,900,50,45000),
("Wales","Desktop",2017,900,20,18000),
("Scotland","Printer",2017,25,25,3000)]
Tip 2:
Implement this function
toString :: Item -> String
toString = undefined -- do this yourselves
Tip 3:
Try to combine the following functions
unlines, already in the Prelude
toString, you just wrote it
map, does not need any explanation
putStrLn, not even sure if this is a real function, but you need it anyway.
($), you can do without this one, but it will give you bonus points

Unable to access all the related predicates in Prolog from C++

I am trying to access all the related predicates of a prolog file from C++.
I have the prolog file as,
"new_gryffindor.pl"
sits_right_of(parvati,lavender).
sits_right_of(lavender,neville).
sits_right_of(neville,alicia).
sits_right_of(alicia,fred).
sits_right_of(fred,george).
sits_right_of(george,lee).
sits_right_of(lee,dennis).
sits_right_of(dennis,dean).
sits_right_of(dean,ginny).
sits_right_of(ginny,angelina).
sits_right_of(angelina,seamus).
sits_right_of(seamus,colin).
sits_right_of(colin,harry).
sits_right_of(harry,hermoine).
sits_right_of(hermoine,ron).
sits_right_of(ron,natalie).
sits_right_of(natalie,katie).
sits_right_of(katie,parvati).
sits_left_of(X,Y) :- sits_right_of(Y,X).
are_neighbours_of(X,Y,Z) :- sits_left_of(X,Z),
sits_right_of(Y,Z).
next_to_each_other(X,Y) :- sits_left_of(X,Y);
sits_right_of(X,Y).
And I have integrated C++ and Prolog file with the C++ code,
term_t a = PL_new_term_ref();
term_t b = PL_new_term_ref();
term_t ans = PL_new_term_ref();
PL_put_variable(ans);
predicate_t p_consult = PL_predicate("consult", 1, "database");
term_t t = PL_new_term_ref();
PL_put_string_chars(t, "new_gryffindor.pl");
PL_call_predicate(NULL, 0, p_consult, t);
fun = PL_new_functor(PL_new_atom("sits_right_of"),2);
PL_cons_functor(ans, fun, a, b);
char *fact1;
char *fact2;
if(PL_call(ans, NULL)) {
PL_get_atom_chars(a, &fact1);
PL_get_atom_chars(b, &fact2);
cout << fact1 << " sits right of " << fact2;
}
This C++ Code is giving me the result for the very first predicate of "sits_right_of" ,i.e, as "parvati sits right of lavender". But I want to print all the related predicates of "sits_right_of" in C++ like the prolog which gives next similar predicate's values by using semicolon ";".
sits_right_of(X,Y).
X = parvati,
Y = lavender ;
X = lavender,
Y = neville ;
X = neville,
Y = alicia ;
X = alicia,
Y = fred ;
X = fred,
Y = george ;
X = george,
Y = lee ;
X = lee,
Y = dennis ;
X = dennis,
Y = dean ;
X = dean,
Y = ginny ;
X = ginny,
Y = angelina ;
X = angelina,
Y = seamus ;
X = seamus,
Y = colin ;
X = colin,
Y = harry ;
X = harry,
Y = hermoine ;
X = hermoine,
Y = ron ;
X = ron,
Y = natalie ;
X = natalie,
Y = katie ;
X = katie,
Y = parvati.
I tried looping statements in C++ but it is printing the same output for multiple times..
So please help me out to print the values of other similar predicates of prolog file in C++.

regular expression for date and time diffrent ways

I am learning regular expression so I did some example. For example I want to validate date dd/mm/yyyy hh:mm:ss or dd-mm-yyy hh:mm:ss
I did like this on https://regex101.com:
([0-9]{2}+[-\/]+[0-9]{2}+[-\/]+[0-9]{4})\s([0-9]{2}+:+[0-9]{2}+:+[0-9]{2})
(\d{2}+[-\/]+\d{2}+[-\/]+\d{4})\s(\d{2}+:+\d{2}+:+\d{2})
Is there any other way to do it so regex can be short? Or it is perfect, I am sure it is not 100% perfect.
i want to add range for example month should not be greater than 12 , in time it should not be grater that 60.
Here is a date validator that I created for this, I think it could be fixed a little but it is working
test()
function dateChecker(re, dOrder, s) {
var validity = {
pass: false,
testString: s
}
s.replace(re, function(full, date, seperator, time) {
var y, m, d, h, min, s, p;
date = date.split(seperator).map(Number);
date[1] --;
time = time ? time.split(':').map(Number) : [0, 0, 0];
p = new Date(
y = date[dOrder.y],
m = date[dOrder.m],
d = date[dOrder.d],
h = time[0],
min = time[1],
s = time[2]);
if (p.getDate() === d &&
p.getMonth() === m &&
p.getFullYear() === y &&
p.getHours() === h &&
p.getMinutes() === min &&
p.getSeconds() === s)
validity.pass = true;
else
validity.failReason = [p, "doesn't match", date, time].join(' ')
});
return validity
}
function dValidator(s) {
return dateChecker(/^((?:\d\d([-\/])){2}\d{4})(?:\s+((?:\d\d:){2}\d\d))?$/, {
d: 0,
m: 1,
y: 2
}, s)
}
function test() {
var failedTests = [],
failData = ["33/09/2064", "31/2/1980"],
sucessData = ["14-03-1904 04:35:17", "29/2/1980"];
failData.map(dValidator).map(function(a, i) {
return a.pass ? failedTests.push([a, i, 'expected to fail but it incorrectly passed']) : console.log('test passed ok', a, i)
})
sucessData.map(dValidator).map(function(a, i) {
return a.pass ? console.log('test passed ok', a, i) : failedTests.push([a, i, 'expected to pass but it has incorrectly failed'])
})
if (failedTests.length) {
console.log(failedTests);
return 'fail'
}
return 'pass'
}
You are using too much +, and you could repeat some groups :
(\d{2}[-\/]){2}\d{4}\s\d{2}(:\d{2}){2}
I found for date m/d/yy or m/d/yyyy or mm/dd/yy or mm/dd/yy
^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$

How to maintain an immutable list when you impact object linked to each other into this list

I'm trying to code the fast Non Dominated Sorting algorithm (NDS) of Deb used in NSGA2 in immutable way using Scala.
But the problem seems more difficult than i think, so i simplify here the problem to make a MWE.
Imagine a population of Seq[A], and each A element is decoratedA with a list which contains pointers to other elements of the population Seq[A].
A function evalA(a:decoratedA) take the list of linkedA it contains, and decrement value of each.
Next i take a subset list decoratedAPopulation of population A, and call evalA on each. I have a problem, because between each iteration on element on this subset list decoratedAPopulation, i need to update my population of A with the new decoratedA and the new updated linkedA it contain ...
More problematic, each element of population need an update of 'linkedA' to replace the linked element if it change ...
Hum as you can see, it seem complicated to maintain all linked list synchronized in this way. I propose another solution bottom, which probably need recursion to return after each EvalA a new Population with element replaced.
How can i do that correctly in an immutable way ?
It's easy to code in a mutable way, but i don't find a good way to do this in an immutable way, do you have a path or an idea to do that ?
object test extends App{
case class A(value:Int) {def decrement()= new A(value - 1)}
case class decoratedA(oneAdecorated:A, listOfLinkedA:Seq[A])
// We start algorithm loop with A element with value = 0
val population = Seq(new A(0), new A(0), new A(8), new A(1))
val decoratedApopulation = Seq(new decoratedA(population(1),Seq(population(2),population(3))),
new decoratedA(population(2),Seq(population(1),population(3))))
def evalA(a:decoratedA) = {
val newListOfLinked = a.listOfLinkedA.map{e => e.decrement()
new decoratedA(a.oneAdecorated,newListOfLinked)}
}
def run()= {
//decoratedApopulation.map{
// ?
//}
}
}
Update 1:
About the input / output of the initial algorithm.
The first part of Deb algorithm (Step 1 to Step 3) analyse a list of Individual, and compute for each A : (a) domination count, the number of A which dominate me (the value attribute of A) (b) a list of A i dominate (listOfLinkedA).
So it return a Population of decoratedA totally initialized, and for the entry of Step 4 (my problem) i take the first non dominated front, cf. the subset of elements of decoratedA with A value = 0.
My problem start here, with a list of decoratedA with A value = 0; and i search the next front into this list by computing each listOfLinkedA of each of this A
At each iteration between step 4 to step 6, i need to compute a new B subset list of decoratedA with A value = 0. For each , i decrementing first the domination count attribute of each element into listOfLinkedA, then i filter to get the element equal to 0. A the end of step 6, B is saved to a list List[Seq[DecoratedA]], then i restart to step 4 with B, and compute a new C, etc.
Something like that in my code, i call explore() for each element of B, with Q equal at the end to new subset of decoratedA with value (fitness here) = 0 :
case class PopulationElement(popElement:Seq[Double]){
implicit def poptodouble():Seq[Double] = {
popElement
}
}
class SolutionElement(values: PopulationElement, fitness:Double, dominates: Seq[SolutionElement]) {
def decrement()= if (fitness == 0) this else new SolutionElement(values,fitness - 1, dominates)
def explore(Q:Seq[SolutionElement]):(SolutionElement, Seq[SolutionElement])={
// return all dominates elements with fitness - 1
val newSolutionSet = dominates.map{_.decrement()}
val filteredSolution:Seq[SolutionElement] = newSolutionSet.filter{s => s.fitness == 0.0}.diff{Q}
filteredSolution
}
}
A the end of algorithm, i have a final list of seq of decoratedA List[Seq[DecoratedA]] which contain all my fronts computed.
Update 2
A sample of value extracted from this example.
I take only the pareto front (red) and the {f,h,l} next front with dominated count = 1.
case class p(x: Int, y: Int)
val a = A(p(3.5, 1.0),0)
val b = A(p(3.0, 1.5),0)
val c = A(p(2.0, 2.0),0)
val d = A(p(1.0, 3.0),0)
val e = A(p(0.5, 4.0),0)
val f = A(p(0.5, 4.5),1)
val h = A(p(1.5, 3.5),1)
val l = A(p(4.5, 1.0),1)
case class A(XY:p, value:Int) {def decrement()= new A(XY, value - 1)}
case class ARoot(node:A, children:Seq[A])
val population = Seq(
ARoot(a,Seq(f,h,l),
ARoot(b,Seq(f,h,l)),
ARoot(c,Seq(f,h,l)),
ARoot(d,Seq(f,h,l)),
ARoot(e,Seq(f,h,l)),
ARoot(f,Nil),
ARoot(h,Nil),
ARoot(l,Nil))
Algorithm return List(List(a,b,c,d,e), List(f,h,l))
Update 3
After 2 hour, and some pattern matching problems (Ahum...) i'm comming back with complete example which compute automaticaly the dominated counter, and the children of each ARoot.
But i have the same problem, my children list computation is not totally correct, because each element A is possibly a shared member of another ARoot children list, so i need to think about your answer to modify it :/ At this time i only compute children list of Seq[p], and i need list of seq[A]
case class p(x: Double, y: Double){
def toSeq():Seq[Double] = Seq(x,y)
}
case class A(XY:p, dominatedCounter:Int) {def decrement()= new A(XY, dominatedCounter - 1)}
case class ARoot(node:A, children:Seq[A])
case class ARootRaw(node:A, children:Seq[p])
object test_stackoverflow extends App {
val a = new p(3.5, 1.0)
val b = new p(3.0, 1.5)
val c = new p(2.0, 2.0)
val d = new p(1.0, 3.0)
val e = new p(0.5, 4.0)
val f = new p(0.5, 4.5)
val g = new p(1.5, 4.5)
val h = new p(1.5, 3.5)
val i = new p(2.0, 3.5)
val j = new p(2.5, 3.0)
val k = new p(3.5, 2.0)
val l = new p(4.5, 1.0)
val m = new p(4.5, 2.5)
val n = new p(4.0, 4.0)
val o = new p(3.0, 4.0)
val p = new p(5.0, 4.5)
def isStriclyDominated(p1: p, p2: p): Boolean = {
(p1.toSeq zip p2.toSeq).exists { case (g1, g2) => g1 < g2 }
}
def sortedByRank(population: Seq[p]) = {
def paretoRanking(values: Set[p]) = {
//comment from #dk14: I suppose order of values isn't matter here, otherwise use SortedSet
values.map { v1 =>
val t = (values - v1).filter(isStriclyDominated(v1, _)).toSeq
val a = new A(v1, values.size - t.size - 1)
val root = new ARootRaw(a, t)
println("Root value ", root)
root
}
}
val listOfARootRaw = paretoRanking(population.toSet)
//From #dk14: Here is convertion from Seq[p] to Seq[A]
val dominations: Map[p, Int] = listOfARootRaw.map(a => a.node.XY -> a.node.dominatedCounter) //From #dk14: It's a map with dominatedCounter for each point
val listOfARoot = listOfARootRaw.map(raw => ARoot(raw.node, raw.children.map(p => A(p, dominations.getOrElse(p, 0)))))
listOfARoot.groupBy(_.node.dominatedCounter)
}
//Get the first front, a subset of ARoot, and start the step 4
println(sortedByRank(Seq(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)).head)
}
Talking about your problem with distinguishing fronts (after update 2):
val (left,right) = population.partition(_.node.value == 0)
List(left, right.map(_.copy(node = node.copy(value = node.value - 1))))
No need for mutating anything here. copy will copy everything but fields you specified with new values. Talking about the code, the new copy will be linked to the same list of children, but new value = value - 1.
P.S. I have a feeling you may actually want to do something like this:
case class A(id: String, level: Int)
val a = A("a", 1)
val b = A("b", 2)
val c = A("c", 2)
val d = A("d", 3)
clusterize(List(a,b,c,d)) === List(List(a), List(b,c), List(d))
It's simple to implement:
def clusterize(list: List[A]) =
list.groupBy(_.level).toList.sortBy(_._1).map(_._2)
Test:
scala> clusterize(List(A("a", 1), A("b", 2), A("c", 2), A("d", 3)))
res2: List[List[A]] = List(List(A(a,1)), List(A(b,2), A(c,2)), List(A(d,3)))
P.S.2. Please consider better naming conventions, like here.
Talking about "mutating" elements in some complex structure:
The idea of "immutable mutating" some shared (between parts of a structure) value is to separate your "mutation" from the structure. Or simply saying, divide and conquerror:
calculate changes in advance
apply them
The code:
case class A(v: Int)
case class AA(a: A, seq: Seq[A]) //decoratedA
def update(input: Seq[AA]) = {
//shows how to decrement each value wherever it is:
val stats = input.map(_.a).groupBy(identity).mapValues(_.size) //domination count for each A
def upd(a: A) = A(a.v - stats.getOrElse(a, 0)) //apply decrement
input.map(aa => aa.copy(aa = aa.seq.map(upd))) //traverse and "update" original structure
}
So, I've introduced new Map[A, Int] structure, that shows how to modify the original one. This approach is based on highly simplified version of Applicative Functor concept. In general case, it should be Map[A, A => A] or even Map[K, A => B] or even Map[K, Zipper[A] => B] as applicative functor (input <*> map). *Zipper (see 1, 2) actually could give you information about current element's context.
Notes:
I assumed that As with same value are same; that's default behaviour for case classess, otherwise you need to provide some additional id's (or redefine hashCode/equals).
If you need more levels - like AA(AA(AA(...)))) - just make stats and upd recursive, if dеcrement's weight depends on nesting level - just add nesting level as parameter to your recursive function.
If decrement depends on parent node (like decrement only A(3)'s, which belongs to A(3)) - add parent node(s) as part of stats's key and analise it during upd.
If there is some dependency between stats calculation (how much to decrement) of let's say input(1) from input(0) - you should use foldLeft with partial stats as accumulator: val stats = input.foldLeft(Map[A, Int]())((partialStats, elem) => partialStats ++ analize(partialStats, elem))
Btw, it takes O(N) here (linear memory and cpu usage)
Example:
scala> val population = Seq(A(3), A(6), A(8), A(3))
population: Seq[A] = List(A(3), A(6), A(8), A(3))
scala> val input = Seq(AA(population(1),Seq(population(2),population(3))), AA(population(2),Seq(population(1),population(3))))
input: Seq[AA] = List(AA(A(6),List(A(8), A(3))), AA(A(8),List(A(6), A(3))))
scala> update(input)
res34: Seq[AA] = List(AA(A(5),List(A(7), A(3))), AA(A(7),List(A(5), A(3))))