Cluster in Haskell - function

How can I define a cluster in Haskell using list comprehension?
I want to define a function for the cluster :
( a b c ) = [ a <- [1 .. 10],b<-[2 .. 10], c = (a, b)]

In your comment you gave the example [(1,2,1),(1,3,1),(1,4,1),(1,5,1),(1,6,1),(1,7,1)].
In that example, only the middle number changes, the other two are always 1. You can do this particular one with
ones = [(1,a,1)| a<-[1..7]]
However, you might want to vary the other ones. Let's have a look at how that works, but I'll use letters instead to make it clearer:
> [(1,a,b)| a<-[1..3],b<-['a'..'c']]
[(1,1,'a'),(1,1,'b'),(1,1,'c'),(1,2,'a'),(1,2,'b'),(1,2,'c'),(1,3,'a'),(1,3,'b'),(1,3,'c')]
You can see that the letters are varying more frequently than the numbers - the b<-[1..3] is like an outer loop, with c<-['a'..'c'] being the inner loop.
You could copy the c into the first of the three elements of the tuple:
> [(b,a,b)| a<-[1..3],b<-['a'..'b']]
[('a',1,'a'),('b',1,'b'),('a',2,'a'),('b',2,'b'),('a',3,'a'),('b',3,'b')]
Or give each its own varying input
> [(a,b,c)| a<-[1..2],b<-['a'..'b'],c<-[True,False]]
[(1,'a',True),(1,'a',False),(1,'b',True),(1,'b',False),(2,'a',True),(2,'a',False),(2,'b',True),(2,'b',False)]

Related

anova_test not returning Mauchly's for three way within subject ANOVA

I am using a data set called sleep (found here: https://drive.google.com/file/d/15ZnsWtzbPpUBQN9qr-KZCnyX-0CYJHL5/view) to run a three way within subject ANOVA comparing Performance based on Stimulation, Deprivation, and Time. I have successfully done this before using anova_test from rstatix. I want to look at the sphericity output but it doesn't appear in the output. I have got it to come up with other three way within subject datasets, so I'm not sure why this is happening. Here is my code:
anova_test(data = sleep, dv = Performance, wid = Subject, within = c(Stimulation, Deprivation, Time))
I also tried to save it to an object and use get_anova_table, but that didn't look any different.
sleep_aov <- anova_test(data = sleep, dv = Performance, wid = Subject, within = c(Stimulation, Deprivation, Time))
get_anova_table(sleep_aov, correction = "GG")
This is an ideal dataset I pulled from the internet, so I'm starting to think the data had a W of 1 (perfect sphericity) and so rstatix is skipping this output. Is this something anova_test does?
Here also is my code using a dataset that does return Mauchly's:
weight_loss_long <- pivot_longer(data = weightloss, cols = c(t1, t2, t3), names_to = "time", values_to = "loss")
weight_loss_long$time <- factor(weight_loss_long$time)
anova_test(data = weight_loss_long, dv = loss, wid = id, within = c(diet, exercises, time))
Not an expert at all, but it might be because your factors have only two levels.
From anova_summary() help:
"Value
return an object of class anova_test a data frame containing the ANOVA table for independent measures ANOVA. However, for repeated/mixed measures ANOVA, it is a list containing the following components are returned:
ANOVA: a data frame containing ANOVA results
Mauchly's Test for Sphericity: If any within-Ss variables with more than 2 levels are present, a data frame containing the results of Mauchly's test for Sphericity. Only reported for effects that have more than 2 levels because sphericity necessarily holds for effects with only 2 levels.
Sphericity Corrections: If any within-Ss variables are present, a data frame containing the Greenhouse-Geisser and Huynh-Feldt epsilon values, and corresponding corrected p-values. "

How to compare two lists in daml

compare1:[Int] -> Book
Compare1[x] =([x] == [x])
Test1 = scenario do
Debug(compare1 [11,12])
What's wrong with the above code why the error daml:44-1-30:Non-exhaustive patterns in function compare1 is appearing?
Let’s look at the crucial line here:
compare1 [x] = [x] == [x]
On the left side of the equal sign you have the pattern match [x]. This only matches a single element list and will bind that single element to the name x. So what the error is telling you that all other cases are not handled (empty lists and lists with more than one element).
To fix that you have two options, either you change the pattern match to just a variable xs (or any other name). That will match any list regardless of the number of elements and bind the list to the name xs.
compare1 xs = …
Alternatively, you can use 2 pattern matches to cover the case where the list is empty and the list has 1 or more elements:
compare1 [] = … -- do something for empty lists
compare1 (x :: xs) = … -- do something with the head of the list bound to `x` and the tail bound to `xs`

erlang output the list length after having it run a quicksort - Part 2

So my first question was answered and it makes sense. It was able to output a list length after a sort, but originally I was asking as a way to use io:format function for a sort/0. But my next follow up, is how to use it with the sort/1? I've been able to work it out to give it, but it's giving it while recursion so I'm getting multiple lines and incorrectly. My question is how do I do the io:format once it's done with quick sort (also note, I also want the list to have no repeats) so I get just the one line of the length instead of the multiple lines I'm getting below?
Here's what I have and am getting:
-module(list).
-export([sort/1]).
sort([]) -> [];
sort([First|Rest]) ->
io:format("~nThe length of the list is ~w~n", [length([First]++Rest)])),
sort([ X || X <- Rest, X < First]) ++
[First] ++
sort([ X || X <- Rest, X > First]).
And the output:
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
The length of the list is 10
The length of the list is 2
The length of the list is 5
The length of the list is 2
The length of the list is 1
[1,2,3,6,8]
So the sorted list with no duplicates is correct, but how do I fit the io:format function in there to show like this?
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
[1,2,3,6,8]
The length of the list is 5
Unless I am mistaken, you are not going to be able to discriminate the usage of io:format/2 inside the recursive function as it is.
You could separate the printing from the recursive part.
sort(L)->
Result = quicksort(L),
io:format("~nThe length of the list is ~w~n", [length(Result)]),
Result.
quicksort([]) -> [];
quicksort([First|Rest]) ->
quicksort([ X || X <- Rest, X < First]) ++
[First] ++
quicksort([ X || X <- Rest, X > First]).

Is there an easy way to sort regressors by the impact they make in Stata?

Instead of the traditional regression output, I want to get a table with two columns A and B. Column A contains a list of regressors and column B contains their impacts which equal:
b_hat(x) / sigma(x)
where b_hat(x) is the marginal effect on the dependent variable due to a 1 unit change in x, and sigma(x) is a standard deviation of x.
It would be great if the list is sorted by impact.
This is a blunt-force way of doing what you want. You can get the idea & use it to write some sort of custom program to do something like this on the fly. This is really rough so I will appreciate comments to make this cleaner or more robust. Right now it would be pretty sensitive to rather minor things.
tempfile temp
sysuse auto, clear
local set "headroom trunk length turn displacement "
foreach var of varlist `set' {
egen `var'_std=std(`var')
}
local set "headroom_std trunk_std length_std turn_std displacement_std "
reg mpg `set'
preserve
mat A=e(b)
clear
set obs 1
g name = "`set'"+"cons"
split name,p(" ")
drop name
g index=_n
reshape long name,i(index) j(num) string
save `temp'
clear
svmat A
g index=_n
reshape long A,i(index) j(num)
tostring num, replace
merge 1:1 num using `temp', nogen assert(3)
drop if name=="cons"
gsort -A
replace num=string(_n)
keep num name index
reshape wide name,i(index) j(num) string
egen ordered=concat(name1-name5),p(" ")
local set2 =ordered[1]
dis "`set'"
dis "`set2'"
restore
reg mpg `set2'
Here's an approach in which the variable names are entered only once. It uses the -mm_ranks- command from Ben Jann's MOREMATA package at SSC and puts the sorted result into a new Stata data set.
sysuse auto, clear
local lhs turn
local rhs length foreign weight
putmata a = (`rhs'), view replace
mata: st_matrix("sd",sqrt(diagonal(variance(a))))
reg `lhs' `rhs'
matrix b = r(table)'
matrix b = b[1..rowsof(b)-1,1]
mata: c = abs(st_matrix("b"):/st_matrix("sd"))
mata: rank = rows(c):-mm_ranks(c):+1 /* SSC package MOREMATA */
mata: st_matrix("n",(c,rank))
mat n = (b, sd, n)
mat colnames n = beta sd impact rank
clear
svmat n , names(col)
tempfile t1
save `t1'
clear
mat np = n'
svmat np, names(col)
keep in 1
xpose, varname clear
keep _varname
qui merge 1:1 _n using `t1'
drop _merge
sort rank
list

Error generating localized variables (as constants)

The usage message for Set reminds us that multiple assignments can easily be made across two lists, without having to rip anything apart. For example:
Remove[x1, x2, y1, y2, z1, z2];
{x1, x2} = {a, b}
Performs the assignment and returns:
{a, b}
Thread, commonly used to generate lists of rules, can also be called explicitly to achieve the same outcome:
Thread[{y1, y2} = {a, b}]
Thread[{z1, z2} -> {a, b}]
Gives:
{a, b}
{z1 -> a, z2 -> b}
However, employing this approach to generate localized constants generates an error. Consider this trivial example function:
Remove[f];
f[x_] :=
With[{{x1, x2} = {a, b}},
x + x1 + x2
]
f[z]
Here the error message:
With::lvset: "Local variable specification {{x1,x2}={a,b}} contains
{x1,x2}={a,b}, which is an assignment to {x1,x2}; only assignments
to symbols are allowed."
The error message documentation (ref/message/With/lvw), says in the 'More Information' section that, "This message is generated when the first element in With is not a list of assignments to symbols." Given this explanation, I understand the mechanics of why my assignment failed. Nonetheless, I'm puzzled and wondering if this is necessary restriction by WRI, or a minor design oversight that should be reported.
So here's my question:
Can anyone shed some light on this behavior and/or offer a workaround? I experimented with trying to force Evaluation, without luck, and I'm not sure what else to try.
What you request is tricky. This is a job for macros, as already exposed by the others. I will explore a different possibility - to use the same symbols but put some wrappers around the code you want to write. The advantage of this technique is that the code is transformed "lexically" and at "compile-time", rather than at run-time (as in the other answers). This is generally both faster and easier to debug.
So, here is a function which would transform the With with your proposed syntax:
Clear[expandWith];
expandWith[heldCode_Hold] :=
Module[{with},
heldCode /. With -> with //. {
HoldPattern[with[{{} = {}, rest___}, body_]] :>
with[{rest}, body],
HoldPattern[
with[{
Set[{var_Symbol, otherVars___Symbol}, {val_, otherVals___}], rest___},
body_]] :>
with[{{otherVars} = {otherVals}, var = val, rest}, body]
} /. with -> With]
Note that this operates on held code. This has the advantage that we don't have to worry about possible evaluation o the code neither at the start nor when expandWith is finished. Here is how it works:
In[46]:= expandWith#Hold[With[{{x1,x2,x3}={a,b,c}},x+x1+x2+x3]]
Out[46]= Hold[With[{x3=c,x2=b,x1=a},x+x1+x2+x3]]
This is, however, not very convenient to use. Here is a convenience function to simplify this:
ew = Function[code, ReleaseHold#expandWith#Hold#code, HoldAll]
We can use it now as:
In[47]:= ew#With[{{x1,x2}={a,b}},x+x1+x2]
Out[47]= a+b+x
So, to make the expansion happen in the code, simply wrap ew around it. Here is your case for the function's definition:
Remove[f];
ew[f[x_] := With[{{x1, x2} = {a, b}}, x + x1 + x2]]
We now check and see that what we get is an expanded definition:
?f
Global`f
f[x_]:=With[{x2=b,x1=a},x+x1+x2]
The advantage of this approach is that you can wrap ew around an arbitrarily large chunk of your code. What happens is that first, expanded code is generated from it, as if you would write it yourself, and then that code gets executed. For the case of function's definitions, like f above, we cansay that the code generation happens at "compile-time", so you avoid any run-time overhead when usin the function later, which may be substantial if the function is called often.
Another advantage of this approach is its composability: you can come up with many syntax extensions, and for each of them write a function similar to ew. Then, provided that these custom code-transforming functions don't conlict with each other, you can simply compose (nest) them, to get a cumulative effect. In a sense, in this way you create a custom code generator which generates valid Mathematica code from some Mathematica expressions representing programs in your custom languuage, that you may create within Mathematica using these means.
EDIT
In writing expandWith, I used iterative rule application to avoid dealing with evaluation control, which can be a mess. However, for those interested, here is a version which does some explicit work with unevaluated pieces of code.
Clear[expandWithAlt];
expandWithAlt[heldCode_Hold] :=
Module[{myHold},
SetAttributes[myHold, HoldAll];
heldCode //. HoldPattern[With[{Set[{vars__}, {vals__}]}, body_]] :>
With[{eval =
(Thread[Unevaluated[Hold[vars] = Hold[vals]], Hold] /.
Hold[decl___] :> myHold[With[{decl}, body]])},
eval /; True] //. myHold[x_] :> x]
I find it considerably more complicated than the first one though.
The tricky issue is to keep the first argument of Set unevaluated.
Here is my suggestion (open to improvements of course):
SetAttributes[myWith, HoldAll];
myWith[{s : Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][
Table[Hold[Set][Extract[Hold[s], {1, 1, i}, Hold],
Extract[Hold[s], {1, 2, i}]], {i, Length#b}], Hold#body]
x1 = 12;
Remove[f];
f[x_] := myWith[{{x1, x2} = {a, b}}, x + x1 + x2]
f[z]
results in
a+b+z
Inspired by halirutan below I think his solution, made slightly more safely, is equivalent to the above:
SetAttributes[myWith, HoldAll];
myWith[{Set[a : {__Symbol}, b_List]} /; Length[a] == Length[b],
body_] :=
ReleaseHold#
Hold[With][
Replace[Thread[Hold[a, b]], Hold[x_, y_] :> Hold[Set[x, y]], 1],
Hold#body]
The tutorial "LocalConstants" says
The way With[{x=Subscript[x, 0],...},body] works is to take body, and replace every
occurrence of x, etc. in it by Subscript[x, 0], etc. You can think of With as a
generalization of the /. operator, suitable for application to Mathematica code instead of
other expressions.
Referring to this explanation it seems obvious that something like
x + x1 + x2 /. {x1, x2} -> {a, b}
will not work as it might be expected in the With notation.
Let's assume you really want to hack around this. With[] has the attribute HoldAll, therefore everything you give as first parameter is not evaluated. To make such a vector-assignment work you would have to create
With[{x1=a, x2=b}, ...]
from the vector-notation. Unfortunately,
Thread[{a, b} = {1, 2}]
does not work because the argument to Thread is not held and the assignment is evaluated before Thread can do anything.
Lets fix this
SetAttributes[myThread, HoldFirst];
myThread[Set[a_, b_]] := mySet ### Transpose[{a, b}]
gives
In[31]:= myThread[{a, b, c} = {1, 2, 3}]
Out[31]= {mySet[a, 1], mySet[b, 2], mySet[c, 3]}
What looks promising at first, just moved the problem a bit away. To use this in With[] you have to replace at some point the mySet with the real Set. Exactly then, With[] does not see the list {a=1, b=2, c=3} but, since it has to be evaluated, the result of all assignments
In[32]:= With[
Evaluate[myThread[{a, b, c} = {1, 2, 3}] /. mySet :> Set], a + b + c]
During evaluation of In[32]:= With::lvw: Local
variable specification {1,2,3} contains 1, which is not an assignment to a symbol. >>
Out[32]= With[{1, 2, 3}, a + b + c]
There seems to be not easy way around this and there is a second question here: If there is a way around this restriction, is it as fast as With would be or do we lose the speed advantage compared to Module? And if speed is not so important, why not using Module or Block in the first place?
You could use Transpose to shorten Rolfs solution by 100 characters:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold[Hold[With][Hold[Set[#1, #2]] & ### Transpose[{a, b}],
Hold#body
]]
#Heike, yep the above breaks if either variable has already a value. What about this:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][Thread[Hold[a, b]] /. Hold[p__] :> Hold[Set[p]],
Hold#body]