Haskell execution sequence - haskell

can anybody help me understand this code
solve s | s == 0 = Nothing
| s == 1 = Just 1
| otherwise =
check [solve (s-(x*2)) | x <- [1..9]]
check x = case x of
[] -> Nothing
(Nothing:xs) -> check xs
(x:xs) -> x
why this gives stack over flow when i tried to run it with even value, and is there any way in haskell where i can debug and see the actual value of the running program , like in eclipse we do ?
thanks

At least with GHCi, there's no way to "step" through code (Edit: no longer true, see comment below), but you can certainly add debug statements using Debug.Trace. In other words if you wanted to check all the recursive calls to solve you could say:
check [trace ("solving for " ++ show (s-(x*2)))) (solve (s-(x*2))) | x <- [1..9]]
There are cleaner ways to write that but that just illustrates the idea.
In this particular case, the reason it recurses infinitely is that the base cases of solve will never be reached. solve 2 for example, resolves to check [solve 0, solve -2, solve -4 ..., solve -16] and solve -2 resolves to check [solve -4, solve -6, ...] etc.

Stack overflow suggests an infinite recursion. Branching on the otherwise case of "solve"
is not guaranteed to terminate. I'm not sure what the code is supposed to be doing here, so I cannot suggest a fix. Hope that helps!

Adding to Dan's answer, you can simply push trace there in solve, and that'll show the problem.
solve s | s == 0 = Nothing
| s == 1 = Just 1
| otherwise =
trace (show s) $ check [solve (s-(x*2)) | x <- [1..9]]

You can rewrite that first parts using pattern matching instead, it's a lot nicer notation than guards (if-statements) ;)
solve 0 = Nothing
solve 1 = Just 1
solve s = check [solve (s - (x * 2)) | x <- [1..9]]
The list comprehension feed the range 1 through 9 to the solve method, which calls solve with
s - (x * 2) and honestly, I can't intuitively tell that that's gonna terminate... but let's consider some examples.
solve 2
Calling solve 2 will result in the following list, since Haskell is lazy that list won't have values until you (have side-effects) try and print these...
solve s - 1 * 2
solve s - 2 * 2
solve s - 3 * 2
solve s - 4 * 2
solve s - 5 * 2
solve s - 6 * 2
solve s - 7 * 2
solve s - 8 * 2
solve s - 9 * 2
A simple solve 2 will try solve -2 which will try and solve other things, and that' won't end.

solve s | s == 0 = Nothing
| s == 1 = Just 1
| otherwise =
check [solve (s-(x*2)) | x <- [1..9]]
In the case of solve 2:
(2 - (1 * 2)) = 0
(0 - (2 * 2)) = -2
et cetera.
I'm not sure about the debugging stuff, but that's why it's overflowing the stack. It's infinitely recursing.

check :: [Maybe a] -> Maybe a
check = Data.Maybe.listToMaybe . Data.Maybe.catMaybes
solve :: (Num a, Num b) => a -> Maybe b
solve 0 = Nothing
solve 1 = Just 1
solve s = solve (s-2)
here, it is pretty obvious that solve -1 and solve 5.3 will run infinite.
this version of solve will run just like a while loop.
the original version you posted will spam in every call unneeded stuff into your ram/stack.
you can rewrite this:
solve s = check [solve (s-x)|x<-[2,4..18]]
to this:
solve s = check [solve (s-2),solve (s-4),solve (s-6),solve (s-8),solve (s-10),solve (s-12),solve (s-14),solve (s-16),solve (s-18)]
but whenever solve (s-2) returns Nothing, then each solve (s-x) will return Nothing, because that value was already tested like this: solve ((((s-2)-2)-2)-2)
it is an exponential algorithm to test sth, which could be tested in linear time or calculated in constant time.
i suggest to read this book:
Haskell: The Craft of Functional Programming

Related

List comprehension not ending in a square bracket, console freezing

Entering a list comprehension into GHCi does not generate a list, the final square brackets are missing, and the console freezes. This is what I have come up with:
[13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000]
I believe the problem lies either with x <- [1..], or 13*x + 3 <= 1000. By 13*x + 3 <= 1000 I meant to determine the upper limit of the values x in x <- [1..] can take.
I'm given back a result [341, but it does the second square bracket is missing, and the console freezes.
Your program enters an infinite loop.
The first number is 341, but in order to produce the next number, your program keeps looking through all the subsequent values of x, evaluates all the guards for those values, and checks if all the guards are true. The very last guard, 13*x + 3 <= 1000 never becomes true again, so the program just keeps enumerating values of x forever. It's looking for the next such x for which all guards are true, and as soon as it finds one, it's going to print it. But such x never comes.
If you want the list to end once x*13 + 3 > 1000, you have to use takeWhile:
... | x <- takeWhile (\y -> y*13 + 3 <= 1000) [1..], ...
That way the list will actually stop when it reaches 1000. No more values of x would be produced.
You're giving the compiler way too much credit. It isn't going to carefully analyse your list comprehension in order to deduce that past a certain point there will be no more results, and it should call the list complete. It only does what you tell it to do.
In this case what you told it to do is:
[ 13*x + 3 -- produce numbers of the form 13*x + 3
| x <- [1..] -- by searching all x from [1..]
, rem (13*x + 3) 12 == 5 -- allowing only x that meet this condition
, mod (13*x + 3) 11 == 0 -- and this condition
, 13*x + 3 <= 1000 -- and this condition
]
So it prints [341 and "freezes" because it's still trying to compute the rest of that list. You don't see anything happening, but internally it's drawing ever bigger x from [1..] and diligently checking those conditions to realise that the number shouldn't be included. But it never hits the end of [1..] in order to stop, so it never gets up to printing the ] and waiting for more input.
With your code you are explicitly telling the compiler that you want to search every number in the infinite1 list [1..]. You are then expecting it to notice that 13*x + 3 <= 1000 can only be true for x drawn from a finite prefix of [1..] and thus actually not search the entire list [1..] as you instructed2.
That is a perfectly reasonable thing to want, and I can imagine a system capable of pulling that off (at least with simple conditions like this). So testing it out like this to see if it works is a good idea! However unless someone actually told you that figuring out enumeration upper bounds from conditions in list comprehensions is a feature that GHC can provide, it shouldn't be surprising that it never completes when you tell it to search an infinite list.
For this style of list comprehension (getting all numbers in a range meeting certain conditions) you normally shouldn't use [1..] and then try to impose a stopping condition. Just figure out that the last number that will pass 13*x + 3 <= 1000 and use [1..76] as your generator instead. You can even have Haskell figure it out for you with [1 .. (1000 - 3) div 13].
You use a generator like [1..] when you want to get all numbers of the right form. Then you can use functions like take or takeWhile to get a finite section at the point where you want to use it for something. e.g.
Prelude> let xs = [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0]
Prelude> takeWhile (<= 1000) xs
[341]
Prelude> take 5 xs
[341,2057,3773,5489,7205]
In fact the simplest and most direct way to express what you want in a single expression is this:
takeWhile (<= 1000) [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0]
Everything in a list comprehension (except the generator expression) is only talking about a single element at a time. There's just no way to express concepts that are talking about the returned list as a whole, like "stop searching once the returned numbers go out of this range". But that concept is trivial to express outside of list comprehension as a normal function (takeWhile (<= 1000)). Don't feel like you have to shoehorn your entire computation into a single list comprehension.
1 Strictly speaking it's infinite if you're using a type like Integer (which is the type Haskell will pick without any other code using the result to impose other constraints on the type). If you're using Int then it's technically finite, and your list comprehension will eventually end when it "runs out of numbers". [1..] as a list of Int is still impractically vast for an exhaustive search, however.
But if you use a smaller type, like Word16 (needs to be imported from Data.Word) then you can in fact finish your original list comprehension in a practical amount of time. (Though I had to tweak it a little to make sure the 13*x stuff was computed in a larger type so it doesn't overflow)
Prelude> import Data.Word
Prelude Data.Word> [13*x + 3 | x <- [1 :: Word16 ..], let x' = fromIntegral x, rem (13*x' + 3) 12 == 5, mod (13*x' + 3) 11 == 0, 13*x' + 3 <= 1000]
[341]
2 While I'm being pedantic in the footnotes, if your original list comprehension is being evaluated as a list of Int it wouldn't even be valid to just stop after x grows high enough that 13*x + 3 <= 1000 fails for the first time. Try this:
Prelude Data.Word> let x = 768614336404564650 :: Int
Prelude Data.Word> 13*x + 3 <= 1000
True
This happens because Int does in fact have an upper bound, so a large enough Int will overflow back to negative when you multiply it by 13. So when searching [1..] as [Int] the compiler is in fact right to keep looking past x = 77; there are almost certainly more numbers in your original list comprehension if it's [Int], they just take a long time to reach.
Again a good way to demonstrate is to use a smaller finite type, like Word16. If I use your original list comprehension as [Word16] without modifying it to avoid overflow in the conditions, you get this:
Prelude Data.Word> [13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000] :: [Word16]
[341,605,209,869,473,77,737]
Even if the compiler was smart enough to know the regions of [1..] that could possibly pass 13*x + 3 <= 1000 condition, it's never going to be able to read your mind and know whether the overflow-produced numbers are solutions you intended or are the result of a bug in your code. It just does what you tell it to do.

why does it return 5 instead of 3 in this code?

Hey guys I have a question regarding the following code: (I use python 3)
def foo (x):
def bar (z, x = 0):
return z + x
return bar(3, x)
foo(2)
Apparently the return value is 5. But no matter how I draw the frame, it comes out returning 3 on my paper. Could someone help me out here? Thanks :)
If I understand correctly your question, you're asking why the program is returning 5 ?
The bar definition in foo acts exactly as if it were defined outside foo function. x is shadowed but it acts like it was completely another variable.
So, when you call foo(2), it calls bar(3, 2) which returns 3+2 = 5.
Formatting the code helps understanding it.
bar(3,x) returns 3+x as x is provided (if x were not provided, it would have been 0 by default.
foo(2) returns bar(3,x) but as x is 2 then you receive 5 as the final response bar(3,2)

Haskell - How to modify existing function values

i have a basic question regarding Haskell that boggles my mind since i am new to functional programming.
i've got simple functions for example
foo 1 1 = 0
foo 1 2 = 1
foo 2 1 = 1
foo 2 2 = 0
and i want to change the function values depending on a condition via another function (for example from 1 to 0, if the value is 1). How can i do that? I'm comming from python and am somehow stuck in the way of thought that i can simply assign the new value in the function body.
im trying something along this lines:
changeValue x y
|(foo x y == 1) = foo x y = 0
A little hint would be appreciated, since it feels like a simple question that i just can't find a solution for. Thanks!
Maybe having a look at http://learnyouahaskell.com/syntax-in-functions helps? Think of haskell functions as mathematical functions, there's no assignment there either.
Anyway, you can ask an other function for a value to compare to, and e.g. in that case return 1:
foo 0 1 = 1
foo x y
| otherfunction x y == 7 = 1
| otherwise = 0

Comprehension - Nested if-conditions in Haskell

i try to become familiar with the if-condition statements in haskell
assume that i´ve an argument x and i try the following in haskell
functionname x = if x > 0 then x-5
if x-5 == 0 then 1
else if x-5 /= 0 then functionname x-5
else if x-5 < then 0
so, the idea was to subtract 5 from x, check if the result is 0, if yes, then give a 1.
If not then invoke the function again with the expression x-5.
If the result of x-5 is negative then give a 0.
so, my questions: Would that be correct? Because when i try that, i´ve got a message like parse error on input 'functionname'.
how can i fix that problem? Are the if-else conditions wrong ?
programm :: Int -> Bool
programm x | x > 0 =
if z == 0 then True
else if z < 0 then False
else programm z
where
z = z-2
programm x | x < 0 =
if z == 0 then True
else if z > 0 then False
else programm z
where
z = z+2
so, i wanted to have the possibility to decide of a given number is even. So, i modify your solution a little bit. its the same but, at the beginning of the two declarations i said : x > 0 = .... and x < 0 =...
Because i want to say that for example -4 is also even. for that reason: the first declarations should handle the positive even numbers and the second declarations handles the negative even numbers.
when i give that to the compiler, then the message : Exception appears. Where i ve made the mistake?
Use guards to make things clear:
functionname x
| x > 0 = x - 5
| x - 5 == 0 = 1
| x - 5 /= 0 = functionname (x - 5)
| x - 5 < 0 = 0
Every if needs to have an else clause associated with it.
The very first one doesn't and the very last one doesn't either.
This works just fine:
functionname x = if x > 0 then x-5
else if x-5 == 0 then 1
else if x-5 /= 0 then functionname x-5
else if x-5 < 0 then 0 else 1
so, the idea was to subtract 5 from x, check if the result is 0, if
yes, then give a 1. If not then invoke the function again with the
expression x-5. If the result of x-5 is negative then give a 0.
That might be written like this:
functionname x =
if x' == 0 then 1
else if x' < 0 then 0
else functionname x'
where
x' = x - 5
Here, I use a where clause to locally define x' as x - 5 and then use it for the tests and the recursive call. Your first branch, if x > 0 then x-5, does not appear in your description of what function should do (it gives x - 5 results as result whenever x is larger than zero, which is probably not what you want). Also, note that every if needs an else as well as a then.
so, i wanted to have the possibility to decide of a given number is
even. So, i modify your solution a little bit. its the same but, at
the beginning of the two declarations i said : x > 0 = .... and x < 0
=... Because i want to say that for example -4 is also even. for that reason: the first declarations should handle the positive even numbers
and the second declarations handles the negative even numbers.
First of all, in the second version of your function the definition in the where clause should be z = x + 2, as z = z + 2 will not terminate. This being an evenness test, you also want to perform the tests on x rather than z. With that fixed, your solution with nested conditionals should work fine (note, however, that you are not treating the x == 0 case; the first guard should be x >= 0). There is a more elegant way of writing the function, though:
myEven :: Int -> Bool
myEven x = myEven' (abs x)
where
myEven' x
| x == 0 = True
| x < 0 = False
| otherwise = myEven' (x - 2)
abs is the familiar absolute value function, while myEven' amounts to the x > 0 branch of your original definition. Taking the absolute value of x is the easiest way to avoid writing two nearly equal branches to handle the negative and non-negative cases.
N.B.: While this is probably just a learning exercise, if you ever need to find whether a number is even there is an even function available from the Prelude. There is also mod if you need to test divisibility for other numbers.

Haskell not in scope list comprehension

all_nat x = [ls| sum ls == x]
I'd like to write a function that given an integer x it returns all the lists that the result of their elements when summed is the integer x but I always get the error "not in scope: 'ls' " for both times it apperas. I'm new to haskell. What's the syntax error here?
The problem is that you need to define all used variables somewhere, but ls is undefined. Moreover, it can't be defined automatically, because the compiler doesn't know about the task — how the list should be generated? Ho long can it be? Are terms positive or not, integral or not? Unfortunately your code definition of the problem is quite vague for modern non-AI languages.
Let's help the compiler. To solve such problems, it's often useful to involve some math and infer the algorithm inductively. For example, let's write an algorithm with ordered lists (where [2,1] and [1,2] are different solutions):
Start with a basis, where you know the output for some given input. For example, for 0 there is only an empty list of terms (if 0 could be a term, any number could be decomposed as a sum in infinitely many ways). So, let's define that:
allNats 0 = [[]] --One empty list
An inductive step. Assuming we can decompose a number n, we can decompose any number n+k for any positive k, by adding k as a term to all decompositions of n. In other words: for numbers greater than 0, we can take any number k from 1 to n, and make it the first term of all decompositions of (n­-k):
allNats n = [ k:rest --Add k as a head to the rest, where
| k <- [1 .. n] --k is taken from 1 to n, and
, rest <- allNats (n - k)] --rest is taken from solutions for (n—k)
That's all! Let's test it:
ghci> allNat 4
[[1,1,1,1],[1,1,2],[1,2,1],[1,3],[2,1,1],[2,2],[3,1],[4]]
Let's break this up into two parts. If I've understood your question correctly, the first step is to generate all possible (sub)lists from a list. There's a function to do this, called subsequences.
The second step is to evaluate the sum of each subsequence, and keep the subsequences with the sum you want. So your list comprehension looks like this:
all_nat x = [ls| ls <- subsequences [1..x], sum ls == x]
What about
getAllSums x = [(l,r)| l <- partial_nat, r <- partial_nat, l + r == x ]
where partial_nat = [1..x]

Resources