syntax - Multiple Statements In Haskell -
How do you have more than one statement in Haskell?
Here's what I'm trying to do: given that a list of [a, b, c, d] comes back to every other element, so you get [a, c] . I can see the solution, and even what I still have:
facts (xs) | Length (xs) `mod` 2 == 1 = head (xs) | Otherwise = the fact (tail (xs))
This works fine around the first time, but then it ends, what I want to be able to say, the head comes back , And then call the truth (tail) (x)) How can I do this?
The specified function returns only one element, you will need something to change:
facts [] = [] - can not call tail on the list of length! Facts (xs) | Length (xs) `mod` 2 == 1 = head (xs): fact (tails (xs)). Fact: tail (xs))
To help you understand such thinkers, typing signatures can be useful: [ A] - & gt; [A] - Change any other list to another (small) list
However note that this is very slow - O (N ^ 2) actually, because it's each Stepping is taking the length on. A lot of Haskelli solution will use pattern matching to process two elements at a time:
Fact :: [A] -> [A] - Take the first element of each two-element pair ... fact (x: _: xs) = x: fact xs- If we only have one element left, then we had a weird-long list. - Then grab the last element too. Fact [x] = [x] - If we do not return anything to an empty list _ = []
Comments
Post a Comment