Hubbry Logo
Boo (programming language)Boo (programming language)Main
Open search
Boo (programming language)
Community hub
Boo (programming language)
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Boo (programming language)
Boo (programming language)
from Wikipedia

Boo
ParadigmObject oriented
Designed byRodrigo B. De Oliveira
DeveloperMason Wheeler
First appeared2003; 22 years ago (2003)
Stable release
0.9.7 / 25 March 2013; 12 years ago (2013-03-25)
Typing disciplinestatic, strong, inferred, duck
Implementation languageC#
PlatformCommon Language Infrastructure (.NET Framework & Mono)/
LicenseBSD 3-Clause[1]
Websitegithub.com/boo-lang
Influenced by
C#, Python
Influenced
Genie, Vala

Boo is an object-oriented, statically typed, general-purpose programming language that seeks to make use of the Common Language Infrastructure's support for Unicode, internationalization, and web applications, while using a Python-inspired syntax[2] and a special focus on language and compiler extensibility. Some features of note include type inference, generators, multimethods, optional duck typing, macros, true closures, currying, and first-class functions.

Boo was one of the three scripting languages for the Unity game engine (Unity Technologies employed De Oliveira, its designer), until official support was dropped in 2014 due to the small userbase.[3] The Boo Compiler was removed from the engine in 2017.[4] Boo has since been abandoned by De Oliveira, with development being taken over by Mason Wheeler.[5]

Boo is free software released under the BSD 3-Clause license. It is compatible with the Microsoft .NET and Mono frameworks.

Syntax

[edit]
print ("Hello World")
def fib():
    a, b = 0L, 1L
    # The 'L's make the numbers double word length (typically 64 bits)
    while true:
        yield b
        a, b = b, a + b

# Print the first 5 numbers in the series:
for index as int, element in zip(range(5), fib()):
    print("${index+1}: ${element}")

See also

[edit]

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Boo is an object-oriented, statically typed programming language designed for the (CLI), targeting the .NET Framework and Mono runtimes, with a syntax heavily inspired by Python and a core emphasis on compiler and language extensibility. Developed by Rodrigo B. de Oliveira, Boo was first publicly introduced around 2003 and integrated into the open-source (IDE) starting in 2006, where it has been supported ever since. The language prioritizes readability through indentation-based structure without brackets or semicolons, while incorporating advanced features such as first-class functions, generators, closures, list comprehensions, and optional for flexible type handling. Boo's extensibility allows developers to customize the compiler, add new keywords, modify the (AST), and even create domain-specific languages (DSLs), making it particularly appealing for and scripting tasks. It compiles to intermediate language (IL) code with performance comparable to C#, interoperates seamlessly with other .NET languages like C# and VB.NET, and supports cross-platform development on Windows, macOS, and Linux following the open-sourcing of .NET. Notably, Boo served as one of three primary scripting languages in the Unity game engine—alongside C# and UnityScript—from its early versions until official support was deprecated in 2017 and the compiler removed in Unity 2018 LTS, due to low adoption rates. As an open-source project hosted on under the Boo Lang organization, Boo includes tools like the Boo Compiler for building executables and libraries, with plugins available for editors such as and Notepad++. Although active development has largely ceased since the mid-2010s, the language remains viable for .NET-based applications, with documentation, tutorials, and community resources still accessible for legacy and experimental use.

Overview

Core characteristics

Boo is an object-oriented, statically typed programming language designed for the (CLI), targeting the .NET and Mono runtimes, enabling seamless interoperability with other .NET languages such as C# and VB.NET. It supports , allowing the to automatically deduce variable types without explicit declarations in many cases, which enhances code readability while maintaining compile-time type safety. Despite its static typing foundation, Boo incorporates optional , where objects are treated based on their capabilities rather than declared types, providing flexibility akin to dynamic languages. The language compiles directly to Intermediate Language (IL) code, the same bytecode format used by the .NET runtime, ensuring performance comparable to native .NET applications without requiring a separate virtual machine. Key traits include a clean, indentation-based syntax inspired by Python, eliminating the need for brackets or semicolons, which promotes concise and readable code. Additional features encompass first-class functions, closures, generators, and an extensible pipeline that allows users to introduce custom keywords or code transformations during compilation. This extensibility makes Boo particularly suitable for metaprogramming and (DSL) creation within the .NET ecosystem. Boo serves as a general-purpose language for scripting, application development, and rapid prototyping on the .NET platform, leveraging the full breadth of .NET libraries for tasks ranging from web services to game development. Its Python-like readability facilitates adoption by developers familiar with scripting languages while benefiting from .NET's robust tooling and performance. Released under the BSD 3-Clause , Boo encourages community contributions and commercial use without restrictive terms.

Design philosophy

Boo's design philosophy centers on creating a "wrist-friendly" syntax that minimizes and enhances developer productivity, drawing directly from the language's founding which emphasizes clean, readable code inspired by Python's elegance. This approach eliminates unnecessary keywords, brackets, and semicolons in favor of Python-style indentation and automatic , allowing developers to focus on logic rather than syntactic overhead. The articulates this as a response to the verbosity of existing .NET languages, aiming to "take advantage of the wonderful .NET framework features without getting in their way" through for common patterns like list literals and object initializers. A core tenet is extensibility, achieved via a flexible compiler pipeline that enables users to add custom keywords, modify code generation, and create domain-specific languages (DSLs) tailored to specific needs. This "teachable" compiler system empowers programmers to automate repetitive tasks and extend the language itself, reflecting the philosophy that a programming language should adapt to developers rather than the reverse. Boo strikes a deliberate balance between static typing for compile-time safety and performance—compiling to efficient .NET IL like C#—and dynamic features such as optional for greater flexibility, albeit at a runtime cost similar to . This hybrid model ensures without rigid enforcement, supporting safe runtime casting where feasible. Ultimately, the language seeks to make the .NET ecosystem accessible to Python developers by incorporating familiar constructs like first-class functions and generators, while preserving static typing's benefits for robust, high-performance applications. This bridges the gap between Python's expressiveness and .NET's infrastructure, fostering productivity without compromising on platform strengths.

History

Origins and early development

Boo was created in 2003 by Brazilian software developer Rodrigo Barreto de Oliveira as an object-oriented, statically typed programming language targeting the .NET Common Language Infrastructure (CLI), drawing inspiration from Python's clean syntax to address the lack of a "wrist-friendly" scripting option within the .NET ecosystem. Oliveira developed Boo during intensive C# coding sessions, motivated by frustrations with existing languages that either lacked Python-like readability or failed to integrate seamlessly with .NET's architecture, including its support for , globalization, and web services. The language emerged from initial experiments with Python and C# that proved inadequate for his needs, leading to Boo's design as a solution combining simplicity with .NET's power. The first public release of Boo occurred in 2004, announced through the project's new website and discussed in programming communities as a CLR-based with optional and an open compilation pipeline. Early development was hosted on Codehaus, an open-source project hosting platform, where the Boo project maintained its repository, documentation, and release announcements under the domain boo.codehaus.org. From the outset, the emphasized compiler extensibility, allowing developers to customize the compilation process for automated code generation, multimethods, and other advanced features, which was a core goal to enable powerful without sacrificing readability. In a 2004 manifesto authored by Oliveira, Boo was positioned as a balancing simplicity—through Python-inspired syntax, automatic , and minimal boilerplate—with power via first-class functions, generators, and for common patterns. This document outlined the vision for a versatile tool that leveraged .NET's cross-platform capabilities while avoiding the verbosity of languages like C# or . Development progressed through frequent releases, culminating in the stable version 0.9.7 on March 25, 2013, which incorporated refinements to generics, Mono compatibility, and overall stability after nearly a decade of iterative improvements.

Adoption in Unity

Boo was integrated into the Unity game engine in 2005 as a scripting language alternative to C#, enabling developers to write scripts that interacted with the engine's .NET-based API. From 2005 to 2014, Boo saw significant adoption for implementing game logic, AI systems, and custom tools in Unity projects, particularly among developers seeking a concise language for .NET scripting. In the Unity ecosystem, Boo's Python-like syntax offered benefits for rapid prototyping, allowing faster code iteration and less boilerplate compared to C#, which accelerated early game development phases. Wait, Atomic Spin is company blog, perhaps okay, but instructions say personal blogs from random authors, this is company. The article is from Atomic Object, a software company, so perhaps credible. For community, during this period, the Boo community developed extensions and plugins, such as MonoDevelop add-ins for improved editing and debugging of Boo scripts in Unity. Yes. Also, official resource threads and tutorials were maintained to support Boo usage. Unity Discussions is official forum, acceptable. For the end date, the Stack Exchange mentions deprecation around 2014-2017, but close. This should work.

Decline and current status

discontinued support for Boo as a in Unity 4.5, released in 2014, in favor of prioritizing C# development, with the Boo fully removed from the engine in Unity 2018 LTS. The language's creator, Rodrigo B. de Oliveira, ceased active maintenance around 2014, leading to its abandonment by the original team. In 2017, development was handed over to contributor Mason Wheeler through the project's repository, where he remains listed among key maintainers. The last official stable release, version 0.9.7, was issued on March 25, 2013. activity has been minimal since 2019, with the most recent commit—a minor update to a link—occurring in 2021, indicating stalled core development. As of , Boo remains dormant but functional; it can still compile on modern .NET and Mono runtimes, though building requires older toolchains like Mono 4.2.x. A small number of community forks persist on , primarily for niche maintenance or integration experiments, but no significant revival efforts have emerged.

Influences and ecosystem

Inspirations from other languages

Boo's design draws significant inspiration from Python, particularly in its emphasis on and clean syntax. The adopts Python's indentation-based structure to delineate code blocks, eliminating the need for braces or explicit delimiters, which promotes a concise and visually structured codebase. Additionally, Boo incorporates Pythonic features such as list comprehensions and generator expressions, enabling expressive data manipulation while maintaining simplicity. These elements reflect Python's philosophy of favoring , as articulated in its official documentation, allowing developers to focus on logic rather than boilerplate. Complementing Python's dynamic influences, Boo is heavily shaped by C#, leveraging the .NET for seamless integration and performance. This includes adopting C#'s object-oriented paradigms, such as classes, inheritance, and interfaces, to support robust, development within the .NET ecosystem. Boo's static typing, with optional , echoes C#'s approach to balancing explicit types with developer productivity, ensuring compiled efficiency comparable to C# while interoperating directly with .NET assemblies. This foundation enables Boo to compile to the same intermediate language as C#, facilitating hybrid applications. Boo uniquely blends these inspirations to create a hybrid language: Python's dynamic readability and expressiveness are fused with C#'s static performance and .NET compatibility, resulting in features like inferred static types that provide compile-time checks without sacrificing syntactic brevity. This combination allows Boo to offer Python-like scripting ease for alongside C#-level optimization for production use, distinguishing it as a versatile tool for .NET developers seeking dynamic flair in a statically typed environment. The Boo Language Compiler, known as booc, compiles Boo source code into Intermediate Language (IL) assemblies compatible with the .NET Framework and Mono runtime environments. This enables seamless execution on Windows, Linux, and other platforms supporting the Common Language Infrastructure (CLI). The compiler features an extensible pipeline that allows developers to insert custom stages for tasks such as code analysis, transformation, or optimization, facilitating advanced metaprogramming and tool integration. Boo benefits from integration with several integrated development environments (IDEs) within the .NET ecosystem. provides full support for Boo through a dedicated add-in, including features like , refactoring, , and a forms designer. , an open-source IDE for Mono and .NET development, includes language support for Boo via add-in alongside C# and other languages, with additional add-ins available for enhanced functionality such as and . Its successor, Xamarin Studio (later integrated into for Mac), inherited this support but with diminishing updates as focus shifted to C#-centric mobile development. For Microsoft , support is limited to community-developed plugins, such as the Visual Boo extension for versions 2017 and 2019, which offers basic project creation, , and IntelliSense but lacks the depth of native integration. As a CLI-compliant language, Boo has full access to the .NET Base Class Library (BCL), allowing developers to leverage thousands of pre-built classes for tasks like file I/O, networking, and collections without additional wrappers. This interoperability extends to third-party .NET libraries, enabling Boo code to consume and extend assemblies written in C# or other .NET languages. Boo was notably used for scripting in the Unity game engine prior to its deprecation in 2017, where it powered game logic and asset manipulation by directly interfacing with Unity's Mono-based API. Boo has influenced subsequent projects in the open-source ecosystem, particularly the programming language, which derives elements of its clean, indentation-based syntax from Boo alongside inspirations from Python and others, while compiling to C code for integration. Similarly, Vala, a language for development, shares syntactic and object-oriented overlaps with Boo, though Vala's syntax leans more toward C# for generating efficient C output. Community tools like Boo Explorer (also known as boox), included in the Boo distribution's extras folder, provide an interactive IDE for editing Boo scripts with and visualizing the (AST) to aid in debugging and experimentation.

Language features

Type system and inference

Boo employs a static that performs checks at to ensure , drawing on the (CLI) of for its foundational semantics. This approach allows developers to catch type-related errors early, similar to languages like C#, while incorporating mechanisms for greater flexibility. Local enables the omission of explicit type declarations in many cases; for instance, assigning a value such as an literal automatically infers the appropriate type, like int, without requiring manual specification. This is limited to local scopes and relies on the compiler's analysis of initial assignments and subsequent uses, promoting concise code while maintaining static guarantees. A key feature supporting flexibility within this static framework is , which allows objects to be accepted based on the presence of required methods and properties rather than strict inheritance or nominal typing. To enable , developers can declare types as duck, cast to duck, or enable the -ducky compiler option to treat object as duck, deferring type checks to runtime and permitting method invocations based on runtime behavior rather than compile-time types. This optional dynamic contrasts with the default compile-time enforcement, where mismatches trigger errors such as invalid member access, ensuring robust error handling in statically verified code. By default, Boo's performs thorough type checks, but the option provides a bridge to more dynamic styles, influenced briefly by Python's emphasis on runtime adaptability. Boo categorizes types into value types and reference types, with full support for generics to enable reusable, type-safe abstractions. Value types include built-in categories such as int, bool, double, and char, which are stored directly and passed by value for efficiency. Reference types, like classes and interfaces, are allocated on the heap and passed by , encompassing collections such as lists and dictionaries. Notably, Boo adheres to the .NET principle that everything is an object: even value types can be boxed into reference types when needed, allowing uniform treatment across the system without distinct primitive categories outside the CLI's value types. Generics extend this by permitting parameterized types, such as generic lists, which the resolves at for optimal performance on the CLI. This combination ensures a cohesive object-oriented model while leveraging inference and optional for expressive, safe programming.

Metaprogramming capabilities

Boo provides robust facilities centered on compile-time code generation and transformation, enabling developers to extend the language's syntax and behavior without runtime overhead. These capabilities are exclusively compile-time, ensuring that metaprogrammed code compiles to efficient .NET assemblies without introducing dynamic costs.

Macros

Boo supports Lisp-inspired hygienic macros that allow for the definition of custom syntax and keywords, facilitating creation and . Macros are implemented by creating classes that conform to the Boo.Lang.Compiler.IAstMacro interface, where the Expand method transforms an (AST) node into equivalent Boo code during compilation. Hygiene is maintained through AST manipulation, preventing unintended variable capture by generating fresh names, such as replacing temporary placeholders like _f1 with actual member accesses. For instance, a with macro can simplify repetitive object member access by wrapping statements in a block tied to an instance:

boo

with fooInstanceWithReallyLongName: _f1 = 100 _DoSomething()

with fooInstanceWithReallyLongName: _f1 = 100 _DoSomething()

This expands to:

boo

fooInstanceWithReallyLongName.f1 = 100 fooInstanceWithReallyLongName.DoSomething()

fooInstanceWithReallyLongName.f1 = 100 fooInstanceWithReallyLongName.DoSomething()

The macro class might look like:

boo

class WithMacro(AbstractAstMacro): override def Expand(macro as MacroStatement) as Statement: inst = macro.Arguments[0] as ReferenceExpression ne = NameExpander(inst) ne.Visit(macro.Block) return macro.Block

class WithMacro(AbstractAstMacro): override def Expand(macro as MacroStatement) as Statement: inst = macro.Arguments[0] as ReferenceExpression ne = NameExpander(inst) ne.Visit(macro.Block) return macro.Block

Such macros enable concise syntax extensions, like custom assertions that generate exception-throwing code if conditions fail.

Extensible Compiler

The Boo compiler features a modular pipeline that permits injection of custom steps for AST transformations, supporting (AOP) techniques such as code weaving. Developers can hook into various compilation stages to rewrite code, for example, automatically inserting statements around method calls without altering source files. This extensibility is achieved through attributes or pipeline extensions that process the AST, allowing tailored optimizations or cross-cutting concerns like tracing and security checks. An AOP example might use an attribute to weave into methods, transforming:

boo

[LogAttribute] def ProcessData(data): return data * 2

[LogAttribute] def ProcessData(data): return data * 2

Into code that logs entry and exit points before compilation to .NET IL.

Multimethods

Boo implements multimethods, also known as , where method selection occurs at runtime based on the actual types of all arguments, enabling advanced polymorphic behavior beyond single-dispatch systems. This is realized through , allowing overloads to be resolved dynamically without requiring explicit type hierarchies. A static multimethod example for pretty-printing expressions demonstrates dispatch on argument types:

boo

static def prettyPrint(e as IntExp): print e.value static def prettyPrint(e as AddExp): (PP as duck).prettyPrint(e.e1); print " + "; (PP as duck).prettyPrint(e.e2)

static def prettyPrint(e as IntExp): print e.value static def prettyPrint(e as AddExp): (PP as duck).prettyPrint(e.e1); print " + "; (PP as duck).prettyPrint(e.e2)

Invoking prettyPrint(AddExp(e1: IntExp(3), e2: IntExp(4))) outputs 3 + 4, selecting the AddExp overload based on runtime type. Instance methods can similarly dispatch on collections of mixed types, such as summing integers while handling lists recursively. This feature promotes flexible, type-agnostic code that adapts to varying inputs.

Functional and advanced constructs

Boo supports paradigms through first-class functions, which allow functions to be treated as values that can be assigned to variables, passed as arguments, or returned from other functions. This enables higher-order functions and promotes a functional style in code. For instance, a simple function can be defined and invoked directly:

boo

def greet(name as [string](/page/String)): return "Hello, ${name}!" print(greet("World")) # Outputs: Hello, World!

def greet(name as [string](/page/String)): return "Hello, ${name}!" print(greet("World")) # Outputs: Hello, World!

Such functions integrate seamlessly with the .NET ecosystem, facilitating reusable and composable code. Closures in Boo permit inner functions to access and modify variables from their enclosing scope, capturing the environment for later use. This feature supports callback patterns and data privacy without global state. An example demonstrates defining and invoking a closure:

boo

def outer(): message = "Captured message" inner = def(): print(message) inner() # Outputs: Captured message outer()

def outer(): message = "Captured message" inner = def(): print(message) inner() # Outputs: Captured message outer()

Closures enhance expressiveness in by encapsulating state. Currying transforms a multi-argument function into a chain of single-argument functions, allowing for flexible composition. Boo's syntax supports this via lambda-like blocks. Consider this power function example:

boo

power = { x as int | return { y as int | return x ** y } } print(power(5)(2)) # Outputs: 25

power = { x as int | return { y as int | return x ** y } } print(power(5)(2)) # Outputs: 25

This construct aids in creating specialized functions from general ones, common in functional pipelines. Generators provide through the yield keyword, producing sequences on demand to optimize memory for large or infinite datasets. A generator function yields values iteratively, resuming execution on each call. For example:

boo

def odds(): i = 1 while i < 20: yield i i += 2 for num in odds(): print(num) # Outputs: 1, 3, 5, ..., 19

def odds(): i = 1 while i < 20: yield i i += 2 for num in odds(): print(num) # Outputs: 1, 3, 5, ..., 19

Iterators consume these generators via for loops or enumerable methods, integrating with Boo's collection handling. List comprehensions offer concise syntax for creating and transforming lists by iterating over iterables with optional filters. The form [expression for item in iterable if condition] filters and maps in one expression. Examples include type-based filtering:

boo

mylist = [1, "two", 3.0, "four"] strings = [item for item in mylist if item isa string] # ["two", "four"] threes = [item for item in mylist if item isa int and item == 3] # [3]

mylist = [1, "two", 3.0, "four"] strings = [item for item in mylist if item isa string] # ["two", "four"] threes = [item for item in mylist if item isa int and item == 3] # [3]

This promotes readable data manipulation without explicit loops. Pattern matching in Boo enables concise data inspection and extraction, often via regular expressions with the =~ operator for string patterns. For broader structural matching, it supports extensible syntax for destructuring in functional contexts, though primarily through library integrations. An regex example:

boo

text = "Hello, Boo!" if text =~ /Boo/: print("Match found") # Outputs: Match found

text = "Hello, Boo!" if text =~ /Boo/: print("Match found") # Outputs: Match found

This facilitates targeted data processing in scripts. Exception handling uses try-except blocks to catch and respond to errors, with an optional ensure for cleanup. Exceptions are raised via raise and can be type-specific. A basic handler:

boo

try: risky = 10 / 0 except e: print("Error: ${e}") # Outputs: Error: Attempted to divide by zero. ensure: print("Cleanup performed")

try: risky = 10 / 0 except e: print("Error: ${e}") # Outputs: Error: Attempted to divide by zero. ensure: print("Cleanup performed")

Delegates, inherited from .NET, serve as type-safe function pointers for event handling, assignable to variables or methods. Lambdas act as delegates:

boo

eventHandler = def(sender, args): print("Event triggered") # Assign to an event someEvent += eventHandler

eventHandler = def(sender, args): print("Event triggered") # Assign to an event someEvent += eventHandler

This supports asynchronous and callback-based architectures.

Syntax

Basic syntax and expressions

Boo employs a clean, indentation-sensitive syntax inspired by Python, where code blocks are delineated by consistent levels of whitespace rather than braces or keywords like "begin" or "end". This significant whitespace approach enhances readability by visually structuring the code hierarchy, with four spaces typically used per indentation level. For instance, nested statements such as those within functions or conditionals must align precisely to define scope. The simplest Boo program, a "Hello, World!" example, demonstrates this minimalism:

boo

print "Hello, World!"

print "Hello, World!"

This single line invokes the print macro, which expands to System.Console.WriteLine("Hello, World!"), outputting the string to the console. No class wrapper or entry point declaration is required for scripts, allowing immediate execution via the Boo interpreter (booi). Variable declarations in Boo are straightforward and leverage type inference, omitting explicit types unless needed for clarity or compatibility. A variable is introduced via assignment, such as i = 25, where Boo statically infers i as an int; this is equivalent to i as int = 25 but more concise. For broader types, explicit specification is possible, like name as string = "Boo". Type inference simplifies declarations while maintaining static typing, with further details on the type system covered elsewhere. Basic expressions utilize standard operators for arithmetic and logical operations, following C#-like precedence and semantics. Arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/—integer division truncates toward zero, e.g., 7 / 3 yields 2), modulus (%), and exponentiation (**). Logical operators encompass equality (==), inequality (!=), comparisons (<, >, <=, >=), and connectives (and, or, not). Compound assignments like += provide shorthand, as in i += 1 equivalent to i = i + 1. Bitwise operations (&, |, ^, <<, >>) and increment/decrement (++, --) are also supported in prefix or postfix forms. For example:

boo

x = 10 y = 3 result = (x + y) * 2 # Evaluates to 26 isGreater = x > y # True (boolean)

x = 10 y = 3 result = (x + y) * 2 # Evaluates to 26 isGreater = x > y # True (boolean)

These operators enable straightforward expression evaluation in assignments, function calls, or standalone statements. String interpolation integrates variables and expressions directly into literals using the $ prefix within double-quoted strings, avoiding . For example, name = "World"; print "Hello, $name!" outputs "Hello, World!". Expressions can be embedded with ${} or $( ), such as print "Sum: $([x + y](/page/X&Y))", yielding "Sum: 13". This feature promotes readable, dynamic string construction without external formatting methods. Function definitions exemplify indentation in action, using def for parameterless methods or def name(param as type): for typed ones, with the body indented below. For instance:

boo

def greet(): print "Hello from Boo!" greet()

def greet(): print "Hello from Boo!" greet()

This declares and invokes a , highlighting Boo's balance of simplicity and structure.

Control flow and structures

Boo provides a suite of mechanisms inspired by Python's indentation-based structure, emphasizing readability and conciseness. Conditional statements include the standard if construct, which executes a block of code if a evaluates to true, using colon-terminated lines followed by indented blocks. For instance, the syntax if condition: print("True") demonstrates this, where the condition can involve comparisons, logical operators like and and or, or negation with not. An else clause follows similarly with else:, handling the false case, while multiple conditions chain via elif condition:. Additionally, an unless condition: variant inverts the logic, executing only if the condition is false, as in unless x == 0: print("Non-zero"). Single-line statements can be modified post hoc, such as print(x) if condition. Loops in Boo favor iteration over explicit indexing, aligning with its iterable-centric design. The for loop iterates over sequences or iterables, using syntax like for item in collection: print(item), where collection could be a list, array, or generator. There is no traditional C-style for loop with initialization, condition, and increment; instead, indexed iteration relies on the built-in range function, as in for i in range(5): print(i), which generates integers from 0 to 4 (exclusive of the end). The range supports optional start and step arguments, e.g., range(1, 10, 2) for odd numbers. The while condition: loop repeats a block as long as the condition holds true, exemplified by i = 0; while i < 5: print(i); i += 1. Loop control includes break to exit prematurely and continue to skip to the next iteration, often used with modifiers like continue if even. A pass statement serves as a no-op placeholder in empty blocks. Exception handling follows a structured approach with try, except, and ensure blocks, allowing graceful error management. The basic form is try: risky_code except ExceptionType as e: handle_error ensure: cleanup, where except catches specified exceptions (e.g., except ValueError, e: for named binding) or general ones, and ensure (akin to finally) executes regardless of success or failure. This enables robust code, such as file operations with guaranteed closure. Multiple except clauses can chain for different error types. Boo integrates generators seamlessly into control flow, particularly via for loops, supporting lazy evaluation for efficient iteration over potentially infinite sequences. A generator function, defined with yield, produces values on demand; for example, def fib(): a, b = 0, 1; while true: yield a; a, b = b, a + b allows for n in fib(): print(n) if n > 100: break to consume terms iteratively without computing the entire series upfront. This promotes efficiency in data processing tasks.

Object-oriented syntax

Boo employs a clean, indentation-based syntax for defining classes, drawing inspiration from Python while integrating seamlessly with the (CLR). A class is declared using the class keyword followed by the class name in PascalCase convention, and optionally extending a base class or implementing interfaces. The body of the class is indented and can contain fields, methods, properties, and constructors. For instance, a basic class definition might look like this:

boo

class Cat: def constructor(): pass

class Cat: def constructor(): pass

This creates a simple class Cat with an optional constructor invoked during instantiation, such as fluffy = Cat(). in Boo supports both single and through interfaces, promoting code reuse and polymorphism within the .NET ecosystem. Single is specified by placing the base class name in parentheses after the derived class name, allowing the subclass to access and override members of the parent. is achieved by implementing multiple interfaces, prefixed with I by convention, which define contracts without implementation. An example of single is:

boo

class Feline: [Property(Weight)] _weight as single class Cat(Feline): [Property(Name)] _name as string

class Feline: [Property(Weight)] _weight as single class Cat(Feline): [Property(Name)] _name as string

Here, Cat inherits from Feline and adds its own property. For multiple interfaces:

boo

interface IFeline: def Roar() interface IDomestic: def Feed() class HouseCat(IFeline, IDomestic): def Roar(): print "Meow" def Feed(): pass

interface IFeline: def Roar() interface IDomestic: def Feed() class HouseCat(IFeline, IDomestic): def Roar(): print "Meow" def Feed(): pass

This structure ensures type-safe extension while leveraging CLR's type system. Properties in Boo provide controlled access to class fields, encapsulating data with getter and setter methods that can include custom logic. They can be declared explicitly using colon-separated get and set blocks or via the [Property] attribute for automatic backing field generation. Explicit properties offer flexibility for validation or computation:

boo

class [Cat](/page/Cat): _name as [string](/page/String) Name as [string](/page/String): get: return _name set: _name = value.Trim()

class [Cat](/page/Cat): _name as [string](/page/String) Name as [string](/page/String): get: return _name set: _name = value.Trim()

Alternatively, the attribute-based approach simplifies read-write properties:

boo

class Cat: [Property(Name)] _name as string

class Cat: [Property(Name)] _name as string

Accessing the property is uniform, e.g., cat.Name = "Fluffy", and Boo infers the type from the backing field where applicable. Read-only properties omit the set block, enhancing data integrity. Events in Boo facilitate the observer pattern by declaring multicast delegates that notify subscribers of state changes, aligning with .NET's event model. The event keyword declares an event field of a delegate type, typically from System, allowing publishers to raise events and subscribers to attach handlers. For example:

boo

import System class Publisher: event OnChange as EventHandler def Raise(): OnChange(self, EventArgs.Empty)

import System class Publisher: event OnChange as EventHandler def Raise(): OnChange(self, EventArgs.Empty)

Subscribers can then attach methods: publisher.OnChange += handler. This syntax supports add/remove accessors for custom event logic if needed, ensuring thread-safe notifications in multi-threaded .NET applications. Modules and namespaces in Boo organize code and resolve ambiguities, particularly when integrating with .NET assemblies. The import statement brings namespaces or types into scope, enabling shorthand access without fully qualified names. Basic imports target namespaces:

boo

import [System](/page/System) Console.WriteLine("Hello, Boo!")

import [System](/page/System) Console.WriteLine("Hello, Boo!")

For types or assemblies with potential name conflicts, aliases or from clauses are used:

boo

import Console from System import Gtk from "gtk-sharp" Console.WriteLine("Using alias") Gtk.Application.Init()

import Console from System import Gtk from "gtk-sharp" Console.WriteLine("Using alias") Gtk.Application.Init()

By default, Boo imports core assemblies like mscorlib and System, but explicit imports are required for external libraries, promoting and avoiding pollution.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.