4

I want to make a list of lists like this:

[1,2,3] [4,5,6] -> [[1,2,3], 4, 5, 6]

This what i have by now:

combine :: [a] -> [a] -> [[a]]
combine xs ys = [xs,ys]

But this code gives me: [[1, 2, 3], [4, 5, 6]] and is not what I need.

2
  • 3
    You can't have the following list: [[1,2,3], 4, 5, 6]. Only this: [[1,2,3], [4], [5], [6]]. You can make this a tuple instead. Commented Apr 16, 2017 at 9:26
  • 1
    To add one to what m0nhawk said, the reason you can't do this is because in Haskell lists are homogeneous. This means every element of the list must the same type. So you can have a list of lists. But you cannot have a list which contains both lists and numbers. This is an XY problem, you think you need this data structure but you don't. What actual problem are you trying to solve? Commented Apr 16, 2017 at 9:50

2 Answers 2

6

As m0nhawk writes in the comments, you can't directly have a Haskell List of both lists of integers and integers. There are several alternatives, though.


One alternative is indeed to use a list of lists of integers ([[1, 2, 3], [4], [5], [6]]), like this:

combine:: [Int] -> [Int] -> [[Int]]
combine xs ys = [xs] ++ [[y] | y <- ys] 

main = do
    putStrLn $ show $ combine [1, 2, 3] [4, 5, 6]               

(running this indeed prints [[1, 2, 3], [4], [5], [6]]).


Another alternative is to use algebraic data types:

Prelude> data ScalarOrList = Scalar Int | List [Int] deriving(Show)
Prelude> [List [1, 2, 3], Scalar 4, Scalar 5, Scalar 6]
[List [1,2,3],Scalar 4,Scalar 5,Scalar 6]
Sign up to request clarification or add additional context in comments.

2 Comments

Incidentally, if you give ScalarOrList instances of both Num and IsList then you can actually write [[1,2,3],4,5,6]. I wouldn't necessarily consider it a good idea, though.
@leftaroundabout Thanks for the useful info!
3

There are such things as heterogeneous lists in Haskell, but they're not particularly trivial or beginner-friendly:

https://hackage.haskell.org/package/hvect-0.4.0.0/docs/Data-HVect.html

This is also a good read: https://wiki.haskell.org/Heterogenous_collections

You're probably best off trying to see if you can make your own data type that encapsulates both simple values and lists of values:

data IntOrList = AnInt Int | AList [Int]

But then you'll have to unwrap your values, which might be an added layer that you don't want to deal with. At least they'll all be able to share a list though: someList = [AnInt 5, AnInt 7, AList [1, 2, 5, 8], AnInt 2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.