D
D
Dmitry Shcherbakov2019-03-22 21:04:17
Haskell
Dmitry Shcherbakov, 2019-03-22 21:04:17

How to generate binary vectors in Haskell?

How to generate binary vectors of a certain length using recursion in Haskell?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2019-03-22
@dsherbakov

If we connect Control.Monad, then all possible binary vectors represented by the list of components are generated by the function

vectors :: Int -> 
vectors n = replicateM n [0, 1]

Instead of [0,1], there can be any other component values ​​(True and False, for example). The n argument specifies the length of the vectors, which will be equal to the number of variables in the boolean expression.
As requested, a new version:
data BinTree = Leaf [Int] | Node BinTree BinTree deriving Show
vars :: Int -> [Int] -> BinTree
vars 1 context = Node (Leaf (0:context)) (Leaf (1:context))
vars n context = Node (vars (n-1) (0:context)) (vars (n-1) (1:context))

Prelude> vars 2 []
Node (Node (Leaf [0,0]) (Leaf [1,0])) (Node (Leaf [0,1]) (Leaf [1,1]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question