Examples of what Lisp's macros can be used for

后端 未结 8 922
自闭症患者
自闭症患者 2020-12-24 05:56

I\'ve heard that Lisp\'s macro system is very powerful. However, I find it difficult to find some practical examples of what they can be used for; things that would be diffi

8条回答
  •  温柔的废话
    2020-12-24 06:31

    Source code transformations. All kinds. Examples:

    • New control flow statements: You need a WHILE statement? Your language doesn't have one? Why wait for the benevolent dictator to maybe add one next year. Write it yourself. In five minutes.

    • Shorter code: You need twenty class declarations that almost look identical - only a limited amount of places are different. Write a macro form that takes the differences as parameter and generates the source code for you. Want to change it later? Change the macro in one place.

    • Replacements in the source tree: You want to add code into the source tree? A variable really should be a function call? Wrap a macro around the code that 'walks' the source and changes the places where it finds the variable.

    • Postfix syntax: You want to write your code in postfix form? Use a macro that rewrites the code to the normal form (prefix in Lisp).

    • Compile-time effects: You need to run some code in the compiler environment to inform the development environment about definitions? Macros can generate code that runs at compile time.

    • Code simplifications/optimizations at compile-time: You want to simplify some code at compile time? Use a macro that does the simplification - that way you can shift work from runtime to compile time, based on the source forms.

    • Code generation from descriptions/configurations: You need to write a complex mix of classes. For example your window has a class, subpanes have classes, there are space constraints between panes, you have a command loop, a menu and a whole bunch of other things. Write a macro that captures the description of your window and its components and creates the classes and the commands that drive the application - from the description.

    • Syntax improvements: Some language syntax looks not very convenient? Write a macro that makes it more convenient for you, the application writer.

    • Domain specific languages: You need a language that is nearer to the domain of your application? Create the necessary language forms with a bunch of macros.

    Meta-linguistic abstraction

    The basic idea: everything that is on the linguistic level (new forms, new syntax, form transformations, simplification, IDE support, ...) can now be programmed by the developer piece by piece - no separate macro processing stage.

提交回复
热议问题