How to combine two lists in Haskell

I want to make a list of such lists:

[1,2,3] [4,5,6] → [[1,2,3], 4, 5, 6]

This is what I have now:

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

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

+4
source share
2 answers

As m0nhawk writes in the comments, you cannot directly have a Haskell list from both lists of integers and integers. However, there are several alternatives.


Alternatively, you can use a list of lists of integers ( [[1, 2, 3], [4], [5], [6]]), for example:

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

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

(performed this really 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]
+6
source

Haskell , , :

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

: https://wiki.haskell.org/Heterogenous_collections

, , , , :

data IntOrList = AnInt Int | AList [Int]

, , . , : someList = [AnInt 5, AnInt 7, AList [1, 2, 5, 8], AnInt 2]

+3

Source: https://habr.com/ru/post/1674912/


All Articles