How can I flatten a nested list like this:
[1, 2, 3, 4] == flatten [[[1,2],[3]],[[4]]]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since nobody else has given this, it is possible to define a function which will flatten lists of an arbitrary depth by using MultiParamTypeClasses. I haven’t actually found it useful, but hopefully it could be considered an interesting hack. I got the idea from Oleg’s polyvariadic function implementation.
Now if you load it and run in ghci:
Note that it’s usually necessary to provide the result type annotation, because otherwise ghc can’t figure out where to stop recursively applying the
flattenclass method. If you use a function with a monomorphic type that’s sufficient however.