Skip to main content

Grammar String Representation

medium
Software engineer

You are working with a toy language grammar that supports three kinds of types: primitives, generics, and tuples. This system is used for defining function types, including parameter and return types.

Type Definitions

  1. Primitive types: "int", "char", "float".
  2. Generic types: Strings following the pattern "T" plus a digit, such as "T1", "T2". A generic can stand for any type.
  3. Tuple types: Represented as a list of types. Tuples may be nested, such as ["int", "char", ["int", "T1"]].

Requirements

You need to implement a class structure that can generate the following string representations:

  • Node.toString():
    • For a primitive or generic, return its value directly (e.g., "int" or "T2").
    • For a tuple, return its children in square brackets, separated by commas (e.g., "[int,T1,char]"). No extra spaces.
  • Function.toString():
    • Returns the function type as "[<param1>,<param2>,...] -> <returnType>".

Implement the TypeSystem class which will be initialized and then called with various methods to build and represent these types.

Example 1

Input

methods: ["TypeSystem", "toString"], arguments: [[], [{"params": ["int", "T1", ["int", "T2"]], "returnType": "T1"}]]

Output

[null, "[int,T1,[int,T2]] -> T1"]

Explanation

The function has three parameters: a primitive 'int', a generic 'T1', and a nested tuple ['int', 'T2']. The return type is 'T1'. Following the rule `[<params>] -> <returnType>`, we get `[int,T1,[int,T2]] -> T1`.

Example 2

Input

methods: ["TypeSystem", "toString"], arguments: [[], [{"params": ["float"], "returnType": ["char", "char"]}]]

Output

[null, "[float] -> [char,char]"]

Example 3

Input

methods: ["TypeSystem", "toString"], arguments: [[], [{"params": [], "returnType": "int"}]]

Output

[null, "[] -> int"]

Constraints

  • All type names are valid strings.
  • The params list and tuple children may be empty.
  • Nesting is allowed to any depth within tuples.
  • params will always be a list, while returnType can be a string or a list (tuple).

Onsite

DesignRecursionStringTree
Language
Code editor loads in the browser.

Output

Input

["TypeSystem","toString"]
[[],[{"params":["int","T1",["int","T2"]],"returnType":"T1"}]]

Expected

[null,"[int,T1,[int,T2]] -> T1"]

Your output

Run to see your output.