Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two lists in Haskell

Tags:

haskell

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.

like image 367
JoeDonald Avatar asked Jan 04 '23 04:01

JoeDonald


1 Answers

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]
like image 168
Ami Tavory Avatar answered Jan 13 '23 02:01

Ami Tavory