I had a question in haskell that asks a function to divide a list in two different lists so the even indexs filled a list and the odd ones another. Example:
func :: [Int] -> ([Int], [Int])
Then, if we enter with [44,8,11,23], we expected receive [44,11] and [8,23]. Looking in the internet I found a great and geniaus solution but can't understand the logic behind it:
func :: [Int] -> ([Int], [Int])
func [] = ([], [])
func [x] = ([x], [])
func (x:y:xs) = (x:odds, y:evens)
where
(odds, evens) = func xs
I know that there are "odd" and "even" functions in haskell, but what would mean "odds" and "evens". How tha values go righty to the certain list? I am drowning in doubt because of this.
I am looking in severals foruns and tutorials to try understand the logic of this code but I am in the zero level until now.
odds&evensare just variable names. They’re not directly related to theodd&evenfunctions. They’re plural (ending ins) because that’s the Haskell naming convention for lists.Let’s work step-by-step through your example input, starting with
func [44, 8, 11, 23].Since this is a recursive function, there will be multiple calls to
func, with their own local variables. To avoid confusion, I will add numbers to the local variables for each call, e.g.x1andx2instead of justx.First,
func [44, 8, 11, 23]matches the third clause offunc,func (x : y : xs).This can be simplified a bit.
Now we need to know the value of
func [11, 23]. This also matches the third clause.And again we can simplify.
Finally,
func []matches the first clause,func [] = ([], []).So we can continue simplifying until we get a solution.