I am new to Haskell and I'm trying to master my skills by transforming this C++ iterative function into Haskell recursion
bool checkStackPermutation(int ip[], int op[], int n) {
queue<int> input;
for (int i=0;i<n;i++)
input.push(ip[i]);
queue<int> output;
for (int i=0;i<n;i++)
output.push(op[i]);
stack <int> tempStack;
while (!input.empty())
{
int ele = input.front();
input.pop();
if (ele == output.front())
{
output.pop();
while (!tempStack.empty())
{
if (tempStack.top() == output.front())
{
tempStack.pop();
output.pop();
}
else
break;
}
}
else
tempStack.push(ele);
}
return (input.empty()&&tempStack.empty());
}
This function is used to check whether the first input array can be transformed into second array using stack, basically it checks whether the first argument is the stack permutation of the second one.
This is what I come up with in Haskell:
get0 (a,b) = a
get1 (a,b) = b
check :: [Integer] -> [Integer] -> [Integer] -> Bool
check input output tempStack
|length input == 0 = (length input) == 0 && (length tempStack) == 0
|head input == head output = check (tail input) (get0 tmp) (get1 tmp)
|otherwise = check (tail input) output (tempStack ++ [head input])
where tmp = aux (tail output) tempStack
aux ::[Integer]->[Integer]->([Integer],[Integer])
aux output tempStack
|length tempStack == 0 = (output,[])
|last tempStack == head output = aux (tail output) (init tempStack)
|otherwise = (output ,tempStack)
But for some reason the output that I obtain from C++ code doesn't match this the Haskell one! I spent a couple of hours trying to find out what I did wrong, but still don't understand.
Can somebody help me to find out what is the problem and explain what I did wrong? Thanks!
UPD
C++
input: [1,2,3] [2,1,3]
output: TRUE
input: [4,1,2,3] [2,1,3,4]
output:FALSE
HASKELL
input: [1,2,3] [2,1,3]
output: TRUE
input: [4,1,2,3] [2,1,3,4]
output:TRUE
Comments
Post a Comment