Prolog Lists with Lists inside - prolog

I'm a total newbie in Prolog I have this code (I'm sorry if its not very friendly to read)
AdjOfAll(State,[FreeSpace],[Result]):-
Adj(State,FreeSpace,Result).
AdjOfAll(State,[Space|NextSpace],[X|Xs]):-
AdjOfAll(State,NextSpace,Xs),
Adj(State,Space,X).
my problem is that Adj returns [ (element_1), ... , (element_n) ]
My objective with AdjOfAll was to get,
[ ( element_1), ..., (element_n), (element_1_from 2nd adj), ... ]
but i get
[ [ ( element_1), ... ,(element_n)] , [ (element_1_from 2nd adj) ], ... ]
I hope its understandable what I'm trying to say, sorry for the bad English

see if flatten/2 can help you to get the right output. Place it after the top level call to AdjOfAll/3.
...
AdjOfAll(State, NextSpace, ResultNested),
flatten(ResultNested, Result),
...
BTW are you sure your predicates are named correctly? Usually they are lowercase.

Related

How do I join elements of an array in Bash and prep the Data for JSON

attribute=( a b c )
I need the array to be held in a variable and show like so:
"a" , "b" , "c"
I suspect this is an XY Problem and you should really be asking about what you want as an end result rather than this micro-issue, but to answer the question you asked -
$: for a in "${attribute[#]}"; do str+="\"$a\" , ";done; str="${str% , }"
$: echo "[$str]"
["a" , "b" , "c"]
For the record, this is probably a bad idea.
Please consider editing your OP to discuss what you want to accomplish and what you have tried. Someone can almost certainly give you a better, safer, smarter solution.

Is it possible to write a rust macro that transposes a matrix?

I am currently working on optimizing the rust jpeg decoder crate using SIMD. In order to avoid long repetitions in the code, I would like to write a macro that generates the following matrix transposition code :
s = [
i32x8::new(s[0].extract(0),s[1].extract(0),s[2].extract(0),s[3].extract(0),s[4].extract(0),s[5].extract(0),s[6].extract(0),s[7].extract(0), ),
i32x8::new(s[0].extract(1),s[1].extract(1),s[2].extract(1),s[3].extract(1),s[4].extract(1),s[5].extract(1),s[6].extract(1),s[7].extract(1), ),
i32x8::new(s[0].extract(2),s[1].extract(2),s[2].extract(2),s[3].extract(2),s[4].extract(2),s[5].extract(2),s[6].extract(2),s[7].extract(2), ),
i32x8::new(s[0].extract(3),s[1].extract(3),s[2].extract(3),s[3].extract(3),s[4].extract(3),s[5].extract(3),s[6].extract(3),s[7].extract(3), ),
i32x8::new(s[0].extract(4),s[1].extract(4),s[2].extract(4),s[3].extract(4),s[4].extract(4),s[5].extract(4),s[6].extract(4),s[7].extract(4), ),
i32x8::new(s[0].extract(5),s[1].extract(5),s[2].extract(5),s[3].extract(5),s[4].extract(5),s[5].extract(5),s[6].extract(5),s[7].extract(5), ),
i32x8::new(s[0].extract(6),s[1].extract(6),s[2].extract(6),s[3].extract(6),s[4].extract(6),s[5].extract(6),s[6].extract(6),s[7].extract(6), ),
i32x8::new(s[0].extract(7),s[1].extract(7),s[2].extract(7),s[3].extract(7),s[4].extract(7),s[5].extract(7),s[6].extract(7),s[7].extract(7), ),
];
The macro should be able to generate the code for different matrix sizes (4 or 8).
I have tried several different approaches, but I never manage to get the macro to repeat n times an n-item pattern.
The most logical to me would be:
macro_rules! square {
(($($x:tt),*), ($($y:tt),*)) => {
[
$([
$( s[$x].extract($y) ),*
]),*
]
};
($($x:expr),*) => { square!( ($($x),*) , ($($x),*) ) };
}
but it fails with
error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
You can do it, but you will need to handle the outer repetition through recursion:
macro_rules! square {
(#row [$($acc:expr),*] [$($before:expr),*] $current:expr $(, $after:expr)*) => {
square!(#row
[ $($acc,)*
stringify!($(s[$current].extract ($before),)*
s[$current].extract ($current)
$(, s[$current].extract ($after))*) ]
[ $($before,)* $current ]
$($after),*)
};
(#row [$($acc:tt)*] [$($before:expr),*]) => { vec![ $($acc)* ] };
($($r:expr),*) => {
square!(#row [] [] $($r),*)
};
}
Playground
I've called stringify! so that the code would compile on the playground without the dependencies. You will need to replace them to fit your needs (probably just remove the stringify! invocation and replace s by an identifier you pass to the macro).
The idea of accumulating the values in $acc and outputting them all at once at the end of the recursion is called the push-down accumulation pattern. If you are not familiar with this concept, it is described in detail in the little book of Rust macros.

Seeking alternative strategy for forming assortative network in netlogo

In my netlogo simulation, I have a population of turtles that have several sociologically-relevant attributes (e.g., gender, race, age, etc.). I want them to form a network that is assortative on multiple of these attributes. The strategy that I’ve been trying to use to accomplish this is to: (i) form all possible links among the turtles, (ii) calculate a propensity to pair index for each of these “potential” links which is a weighted linear combination of how similar two turtles on the relevant attributes, and (iii) then run a modified version the “lottery” code from the models library so that links with higher propensities to pair are more likely to be selected, the selected links are then set to be “real” and all the potential links that didn’t win the lottery (i.e., are not set to real) are deleted. The problem that I’m running into is that forming all possible links in the first steps is causing me to run out of memory. I’ve done everything I can to maximize the memory that netlogo can use on my system, so this question isn’t about memory size. Rather, it’s about modeling strategy. I was wondering whether anyone might have a different strategy for forming a network that is assortative on multiple turtle attributes without having to form all potential links. The reason I was forming all potential links was because it seemed necessary to do so in order to calculate a propensity to pair index to use in the lottery code, but I’m open to any other ideas and any suggestions would be greatly appreciated.
I’m including a draft of the modified version of the lottery code I’ve been working, just in case it’s helpful to anyone, but it may be a little tangential since my question is more about strategy than particular coding issues. Thank you!
to initial-pair-up
ask winning-link [set real? true]
end
to-report winning-link
let pick random-float sum [propensitypair] of links
let winner nobody
ask not real? links
[if winner=nobody
[ifelse similarity > pick
[set winner self] [set pick pick-similarity] ] ]
report winner
end
For a "lottery" problem, I would normally suggest using the Rnd extension, but I suspect it would not help you here, because you would still need to create a list of all propensity pairs which would still be too big.
So, assuming that you have a propensity reporter (for which I've put a dummy reporter below) here is one way that you could avoid blowing up the memory:
to create-network [ nb-links ]
; get our total without creating links:
let total 0
ask turtles [
ask turtles with [ who > [ who ] of myself ] [
set total total + propensity self myself
]
]
; pre-pick all winning numbers of the lottery:
let picks sort n-values nb-links [ random-float total ]
let running-sum 0
; loop through all possible pairs...
ask turtles [
if empty? picks [ stop ]
ask turtles with [ who > [ who ] of myself ] [
if empty? picks [ stop ]
set running-sum running-sum + propensity self myself
if first picks < running-sum [
; ...and create a link if we have a winning pair
create-link-with myself
set picks but-first picks
]
]
]
end
to-report propensity [ t1 t2 ]
; this is just an example, your own function is probably very different
report
(1 / (1 + abs ([xcor] of t1 - [xcor] of t2))) +
(1 / (1 + abs ([ycor] of t1 - [ycor] of t2)))
end
I have tried it with 10000 turtles:
to setup
clear-all
create-turtles 10000 [
set xcor random-xcor
set ycor random-ycor
]
create-network 1000
end
It takes a while to run, but it doesn't take take much memory.
Maybe I have misunderstood, but I am unclear why you need to have the (potential) link established to run your lottery code. Instead, you could calculate the propensity for a pair of nodes (nodeA and nodeB) and create a link between them if the random-float is lower than the propensity. If you want it proportional to the 'share' of the propensity, calculate the total propensity over all pairs first and then the probability of creating the link is this-pair-propensity / total-propensity.
Then the only issue is running through each pair exactly once. The easiest way is probably an outer loop (nodeA) of all agents and an inner loop of agents (nodeB) with a who number that is greater than the outer loop asker (myself). Something like:
to setup
clear-all
create-turtles 30
[ set xcor random-xcor
set ycor random-ycor
]
ask turtles
[ ask turtles with [ who > [who] of myself ]
[ if random-float 1 < 0.4 [create-link-with myself]
]
]
end

Ruby - Why is this reverse sort not working correctly?

I have code that's sorting an array of arrays of objects based on a common method/value all objects share, but it's not quite working correctly. The code is supposed to give me the X highest totals based on the added value, but if I do .first(10) it misses the top values. If I do first(50), I see more, but there's still some higher values missing. What's going on here, shouldn't my sort and reverse ensure that first(x) will return the array with the highest sum? It seems first is grabbing without the sort being completed.
some_array = old_array.sort_by{ |ar| ar.sum(&:ppd) }.reverse.first(10)
Here's an example of what old_array looks like in case it adds clarity
old_array = [
[ obj1, obj2 ], #obj1.ppd + obj2.ppd = 50
[ obj3, obj4 ], #sum ppd = 55
[ obj5, obj6 ], #sum ppd = 60, does not show in first(10)
... #and so on with dozens more
]

How to call a constructed quotation in Factor

I have a word which constructs a quotation which I want to be called. However, when I load the code I get Cannot apply “call” to a run-time computed value. If I use the walker and step thru the code it executes as expected. How are you supposed to call a constructed quotation?
: ba>struct ( array class -- struct array )
[ <struct> swap ] keep struct-slots
[
[ type>> to-type ] keep
name>> setter-word 1quotation curry
[ over ] dip curry call drop
] each
;
EDITED: This does work
: ba>struct ( array class -- struct array )
[ <struct> swap ] keep struct-slots
[
[ type>> to-type ] keep
name>> setter-word 1quotation curry
[ over ] dip curry call( -- x ) drop
] each
;
The problem stems from the runtime not knowing what the stack effect is of a constructed quote. In these cases, you must declare what the stack looks like to the quote for the call.

Resources