haskell - List of all Collatz sequences from 1 to n -
I am trying to program a function that calculates the summation sequence of all the numbers from 1 to n. The result should be in the list of lists.
Something like this:
collatzSeqs 5 => [1], [2, 1], [3, 10, 5, 16, 8, 4, 2, 1], [4, 2, 1], [5, 16, 8, 4, 2, 1]]
My code looks like this:
nextCollatz :: int-> Int next colts N & lt; 1 = Error "less than 1". N == 1 = 1 | Mod n 2 == 0 = div n 2 | Otherwise = 3 * n + 1 - next collet number choltexax :: int-> Counts. [Int] Collazsack N. | N & lt; 1 = Error "less than 1". N == 1 = [1] | Otherwise = n: collatzSeq (nextCollatz n) - Creates a sequence sequence sequence
The idea is that I had to program CollatzSeqs
head [ CollatzSeq]
and somehow to continue it in a recursive form and then take the results and insert it into a new list which is probably empty
to clarify my view I have tried to clear it out: (This does not work)
collatzSeqs :: [int] - & gt; [[Int]] collatzSeqs n = collatzSeq head [1..n]: []
collatzSeqs
, we see that it takes an input n
and returns a list of the list containing the list 1
. This is generated by the fact that there is actually no recursive call here. All functions take an integer and for 1, the collate sequence returns to empty list like this: - Example 3: collatzSeqs 3 = collatzSeq (head [1..n]) : [] = CollatzSeq 1: [] = [1]: [] = [[1]]
We can see that the n function for any input is only [ [1]]
. The problem is that there are no recursive here. If we rewrite this function we will do something like this:
collatzSeqs n = collatzHelp n 1 where collatzHelp n m. N == M = Collett SEEC N: [] | Otherwise collatzSeq m: collatzHelp n (m + 1)
But it is complicated, obviously something should be simple because what we want to do is just take one function and implement it You have a list and fortunate for each element, there really is!
Your collatzSeqs
is actually just a simple map:
A map is a function that takes the function and a list and gives a list of the results of the function that is applied to each element of the given list. You can imagine defining it like this:
map f [] = [] map f (x: xs) = fx: map f xs
In this case, we want to calculate for each element collatzSeq
and our list should be number one from n because we want the function applied in every number between 1 and n . / P>
Comments
Post a Comment