haskell card filter [closed] - haskell

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a group of cards
initialCards :: GameState
initialCards = [[Card s1 r1, Card s2 r2] | s1 <- [minBound .. maxBound]::[Suit], r1 <- [minBound.. maxBound]::[Rank],
s2 <- [minBound .. maxBound]::[Suit], r2 <- [minBound .. maxBound]::[Rank],
s1 /= s2, r1 /= r2]
for example , i want to keep the [Card], which have rank Suit and Diamond,
how can i write the code.

You use the filter function on the list of cards and supply it with a function that maps Suits and Diamonds to True.

Related

How to calculate a polynomial equation in haskell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Basically I need to calculate a polynomial in haskell based on a value x, and the values of the coeficients need to be stored in a list of tupples.
So for example the polynomial f(x) = a·xn + a1·xn−1 + ... + an−1·x + an will be represented in a list of tuples like f = [(a0, n), (a1, n-1), ... , (an-1, 1), (an, 0)] , so if I want to calculate
2*x^2 + 3*x + 3 for x=20 I will need the list [(2,2), (3,1) , (0,3)].
Thanks a lot in advance and sorry if I explained this exercise in a messy way :)
If you want a basic solution, try using explicit recursion:
evaluate :: [(Int, Int)] -> Int -> Int
evaluate [] _x = .... -- TODO (1)
evaluate ((a,n) : rest) x = .... -- TODO (2)
where
result = evaluate rest x
Above, in (1) we need to specify what is the result of evaluating an "empty" polynomial (with no coefficients at all). This is the base case of our recursion.
Instead, (2) is the recursive step. Here, we split the coefficients-pairs into the first (a,n), and the rest of the list rest. We then recursively define result = evaluate rest x to evaluate the polynomial "without the first coefficient", that is a1·xn−1 + ... + an−1·x + an.
Then, in line (2) we need to combine this result with the first monomial, evaluated in x.
You should now be able to fill the dots.
Easy: just fold over the list. The accumulator function should add the current term (solved for x) to the accumulate. The seed needs to be 0, of course.
something like this
> peval p x = foldr (\(a,n) s -> s+(a*x^n)) 0 p
> poly = peval [(2,2),(3,1),(3,0)]
> map poly [0..5]
[3,8,17,30,47,68]

how to make an optimal combinatorial selection in R

The problem I'm trying to solve is basically the same as the one in this post:
https://stats.stackexchange.com/questions/339935/python-library-for-combinatorial-optimization
And my current implementation uses indeed a genetic algorithm based optimizer.
However, I would like to solve it as a binary linear programming problem (at least try, even though it's 'NP-hard', apparently).
My question is how to formulate the LP in the best way, because I am not sure I am doing it right.
The following is a simplified version of what I'm dealing with, which however shows exactly where the problem lies.
We make m*n (in this case 6) objects by a combinatorial process taking m (3) objects of type 'R1' (say {A,B,C}) and n (2) objects of type 'R2' (say {X,Y}).
The 6 objects {AX,AY,BX,BY,CX,CY} are evaluated and each gets a score D, in this case {0.8,0.7,0.5,0.9,0.4,0.0}, in this order.
CL <- cbind(expand.grid(R2=LETTERS[24:25],R1=LETTERS[1:3],stringsAsFactors = FALSE),D=c(0.8,0.7,0.5,0.9,0.4,0.0))
Now we want to select 2 distinct R1's and 1 R2 such that the sum of D is maximal.
In this example, the answer is R1 = {A,B}, R2 = {Y}.
However, one would not get to such conclusion taking, for instance, the 2 R1's and the R2 with the highest average D.
It would work for R1, but not for R2:
aggregate(D~R1,CL,mean)
# R1 D
#1 A 0.75
#2 B 0.70
#3 C 0.20
aggregate(D~R2,CL,mean)
# R2 D
#1 X 0.5666667
#2 Y 0.5333333
I know how to formulate this as a linear programming problem; only I am not sure my formulation is efficient, because basically it results in a problem with mn+m+n variables and 2(m+n)+2 constraints.
The main difficulty is that I need somehow to count the number of distinct R1's and R2's chosen, and I don't know any way of doing that apart from what I will show below (and is also described in my other post here).
This is what I would do:
CL["Entry"] <- seq_len(dim(CL)[[1]])
R1.mat <- table(CL$R1,CL$Entry)
R2.mat <- table(CL$R2,CL$Entry)
N_R1 <- dim(R1.mat)[[1]]
N_R2 <- dim(R2.mat)[[1]]
N_Entry <- dim(CL)[[1]]
constr.mat <- NULL
dir <- NULL
rhs <- NULL
constr.mat <- rbind(constr.mat,cbind(R1.mat,-diag(table(CL$R1)),matrix(0,N_R1,N_R2)))
dir <- c(dir,rep("<=",N_R1))
rhs <- c(rhs,rep(0,N_R1))
constr.mat <- rbind(constr.mat,cbind(R2.mat,matrix(0,N_R2,N_R1),-diag(table(CL$R2))))
dir <- c(dir,rep("<=",N_R2))
rhs <- c(rhs,rep(0,N_R2))
constr.mat <- rbind(constr.mat,constr.mat)
dir <- c(dir,rep(">=",N_R1+N_R2))
rhs <- c(rhs,1-table(CL$R1),1-table(CL$R2))
constr.mat <- rbind(constr.mat,c(rep(0,N_Entry),rep(1,N_R1),rep(0,N_R2)))
dir <- c(dir,"==")
rhs <- c(rhs,2)
constr.mat <- rbind(constr.mat,c(rep(0,N_Entry),rep(0,N_R1),rep(1,N_R2)))
dir <- c(dir,"==")
rhs <- c(rhs,1)
obj <- c(aggregate(D~Entry,CL,c)[["D"]],rep(0,N_R1+N_R2))
Which can be solved for instance by lpSolve:
sol <- lp("max", obj, constr.mat, dir, rhs, all.bin = TRUE,num.bin.solns = 1, use.rw=FALSE, transpose.constr=TRUE)
sol$solution
#[1] 0 1 0 1 0 0 1 1 0 0 1
showing that products {AY,BY} were selected, corresponding to R1 = {A,B} and R2 = {Y}:
CL[as.logical(sol$solution[1:N_Entry]),]
# R2 R1 D Entry
#2 Y A 0.7 2
#4 Y B 0.9 4
I found that on large problems lpSolve gets stuck for ages; Rsymphony seemed to perform better.
But again, my main question is: is this way of formulating the LP efficient? Should I do it differently?
Thanks!
EDIT
In the meantime, working on a somewhat related problem, I found that only one set of constraints may be sufficient, if one adds 'costs' (in this example, negative) to the objective vector for the 'distinct R1 and R2' variables.
So here, instead of:
obj <- c(aggregate(D~Entry,CL,c)[["D"]],rep(0,N_R1+N_R2))
I would do:
obj <- c(aggregate(D~Entry,CL,c)[["D"]],rep(-1,N_R1+N_R2))
This would make m+n constraints unnecessary.
It still remains a huge problem to solve, even for relatively small m, n, so if anyone can advise how to do it better...
I had a look at lp.transport, but that would be limited to 2 dimensions (i.e. only R1 and R2, not R1, R2, R3 for instance), and I don't think you can constrain the number of distinct objects per category in that kind of solver.

Showing that the intersection of two language accepted by NFA is undecidable

I am having problem with this problem.
Let A = {〈N1, N2〉 | N1 and N2 are NFAs and L(N1) ∩ L(N2) =∅}. Show that A is decidable.
Any help is appreciated.
Given an input , here is an algorithm that determines whether L(N1) ∩ L(N2) =∅:
determinize N1 and N2 into D1 and D2 using the powerset construction. slow, but effective.
intersect D1 and D2 into M using the Cartesian product machine construction.
minimize M into M' using some DFA minimization algorithm
see whether M' has an accepting state. if so, halt-reject; otherwise, halt-accept.
This is an effectively computable procedure for determining inclusion and/or exclusion from the set, so the set is decidable.

Haskell Define a numeratic type with bounds

I'm learning Haskell and want to see explore the best practic coding functions with probabilitics distributions.
When coding with probablistic functions, it is typical that a function should return a Float value witin in [0, 1].
Is it possible to define a "Probability" data type that can only take values within that range ?
Thanks very much!
Tao
What you ask is not simple. Personally, I would rather use a function like this one:
checkBounds :: (Real a, Show a) => a -> a
checkBounds x | 0 <= x && x <= 1 = x
| otherwise = error $ show x ++ " is not in [0,1]"
But if you want to go further, have a look at this article, the probability package and this code snippet, maybe they could help.

Recursive arithmetic sequence in Haskell

It's been nearly 30 years since I took an Algebra class and I am struggling with some of the concepts in Haskell as I work through Learn you a Haskell. The concept that I am working on now is "recursion". I have watched several youtube videos on the subject and found a site with the arithmetic sequence problem: an = 8 + 3(an-1) which I understand to be an = an-1 + 3 This is what I have in Haskell.
addThree :: (Integral a) => a -> a
addThree 1 = 8
addThree n = (n-1) + 3
Running the script yields:
addThree 1
8
addThree 2
4
addThree 3
6
I am able to solve this and similar recursions on paper, (after polishing much rust), but do not understand the syntax in Haskell.
My Question How do I define the base and the function in Haskell as per my example?
If this is not the place for such questions, kindly direct me to where I should post. I see there are Stack Exchanges for Super User, Programmers, and Mathematics, but not sure which of the Stack family best fits my question.
First a word on Algebra and you problem: I think you are slightly wrong - if we write 3x it usually means 3*x (Mathematicans are even more lazy then programmers) so your series indeed should look like an = 8 + 3*an-1 IMO
Then an is the n-th element in a series of a's: a0, a1, a2, a3, ... that's why you there is a big difference between (n-1) and addThree (n-1) as the last one would designate an-1 while the first one would just be a number not really connected to your series.
Ok, let's have a look at your series an = 8 + 3an-1 (this is how I would understand it - because otherwise you would have x=8+3*x and therefore just x = -4:
you can choose a0 - let's say it`s 0 (as you did?)
then a1=8+3*0 = 8
a2=8+3*8 = 4*8 = 32
a3=8+3*32 = 8+3*32 = 104
...
ok let's say you want to use recursion than the problem directly translates into Haskell:
a :: Integer -> Integer
a 0 = 0
a n = 8 + 3 * a (n-1)
series :: [Integer]
series = map a [0..]
giving you (for the first 5 elements):
λ> take 5 series
[0,8,32,104,320]
Please note that this is a very bad performing way to do it - as the recursive call in a really does the same work over and over again.
A technical way to solve this is to observe that you only need the previous element to get the next one and use Data.List.unfoldr:
series :: [Integer]
series = unfoldr (\ prev -> Just (prev, 8 + 3 * prev)) 0
now of course you can get a lot more fancier with Haskell - for example you can define the series as it is (using Haskells laziness):
series :: [Integer]
series = 0 : map (\ prev -> 8 + 3 * prev) series
and I am sure there are much more ways out there to do it but I hope this will help you along a bit

Resources