I suspect by "How can I print every combination?", what you mean is "How do I get the x
and y
values that gave me the appropriate sum?". The minimal fix is to have the list comprehension return x
, y
, and the sum all at once, and modify your filter
and dropWhile
to ignore the x
and y
bits. Thus:
func = id
. filter (\(x,y,sum) -> sum > 9)
. takeWhile (\(x,y,sum) -> sum < 100)
. nub
$ [(x,y,floor (sqrt (x) + sqrt (y))) | x <- [0..], y <- [0..]]
There is also a nubBy
that may interest you. However, there remain many "thinkos" that you should address, one at a time:
func
is a bad name; the name implies that it is a function, which isn't true.
- You are not checking that the
sqrt
s add to an integer; instead, you are forcing their sum to be an integer.
Your iteration strategy will never choose an x
other than 0
. You should either limit the upper bounds of your iterations by a known worst-case, e.g. by
x <- [0..100^2], y <- [0..100^2]
or apply the fix described in another of my answers.
- Once you have fixed the previous bit, you will notice that the sums are not monotonically increasing. This means that your
takeWhile
strategy for deciding when to stop will not be correct.
- Once you have had some practice fixing this algorithm, you should rethink whether this is the right algorithm to use. (i.e. why are we iterating over so many
x
and y
values which are not squares?)