I’m trying to figure out a solution for Problem 27 of 99 Haskell questions.
Here’s how I want it to be:
group :: (Eq a) => [Int] -> [[a]] -> [[[[a]]]]
group [] _ = []
group (i:is) xs
| sum (i:is) /= length xs = error "invalid arguments"
| otherwise = ...
An example from the link:
group [2,2,5] [“aldo”,”beat”,”carla”,”david”,”evi”,”flip”,”gary”,”hugo”,”ida”]
[[[“aldo”,”beat”],[“carla”,”david”],[“evi”,”flip”,”gary”,”hugo”,”ida”]],…]
(altogether 756 solutions)
Thus, I want to firstly check whether the sum of Int list equals to the length String list as above. What I run into is that no matter whether the two values equal or not it always print “invalid arguments”. I also tried this:
group (i:is) xs
| (sum (i:is) == length xs) = ...
| otherwise = error "invalid arguments"
still doesn’t work
Any ideas?
UPDATES: thanks guys, my carelessness. Here’s the recursive part of the function:
group (i:is) xs
| (sum (i:is) == length xs) = filter (/= []) $ concatGroups (combinations i xs) (group is xs)
| otherwise = error ("invalid arguments: " ++ show (sum(i:is)) ++ "/=" ++ show(length xs))
As you can tell, group is xs reduces the sum but not the length so it will always complain when going recursive. I think I will just remove that guard and wish the user would never do it wrong.
To expand on hammar’s point, if you change your code to
this will help you track down what is going wrong in the
...part.