Search code examples
grammarbnf

BNF to create vectors with same lengths


Is it possible to describe in BNF a pair of vectors of the same length? For instance, I would like to use such a grammar to capture valid dot product operations as such an operation requires vectors of the same length.

I can describe one vector (I think this is okay): [1,2,3]

<vector> ::= "[" <vectorItems> "]"
<vectorItems> ::= <wholeNumber>|<wholeNumber>","<vectorItems>

But how can I describe the following (that is, the vectors can be of any length but the lengths of the two vectors are the same; Is this even possible? I am kind of new at this)?: [1,2,3,4], [5,6,7,8]


Solution

  • Something like this?

      S := [T]
      T := N,T,N | N],[N
      N := (any valid number)
    
      Nonterminals: S, T, N
      Terminals: [ ] , # (anything required by your definition of N)
    

    The strings in this language are, in order from smallest to largest, where N stands for an arbitrary number:

    L = { [N],[N], [N,N],[N,N], [N,N,N],[N,N,N], ...}

    = {aBcDe | a=[ and c=],[ and e=] and B=(N,)^k N and D=(N,)^k N and k > 0)

    (terminal symbols shown in bold)