Recent from talks
Nothing was collected or created yet.
Boo (programming language)
View on Wikipedia
This article needs additional citations for verification. (July 2011) |
| Boo | |
|---|---|
| Paradigm | Object oriented |
| Designed by | Rodrigo B. De Oliveira |
| Developer | Mason Wheeler |
| First appeared | 2003 |
| Stable release | 0.9.7
/ 25 March 2013 |
| Typing discipline | static, strong, inferred, duck |
| Implementation language | C# |
| Platform | Common Language Infrastructure (.NET Framework & Mono)/ |
| License | BSD 3-Clause[1] |
| Website | github |
| 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]This section may need to be rewritten to comply with Wikipedia's quality standards. (May 2023) |
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]- ^ "license.txt". github.com. Retrieved August 5, 2015.
- ^ Rodrigo Barreto de Oliveira (2005). "The boo Programming Language" (PDF). Archived from the original (PDF) on February 6, 2009. Retrieved February 22, 2009.
- ^ aleksandr (September 3, 2014). "Documentation, Unity scripting languages and you". Unity Blogs.
- ^ Richard Fine (August 11, 2017). "UnityScript's long ride off into the sunset". Unity Blogs.
- ^ "State of Boo · Issue #201 · boo-lang/boo". GitHub. October 2, 2019. Retrieved January 19, 2023.
External links
[edit]Boo (programming language)
View on GrokipediaOverview
Core characteristics
Boo is an object-oriented, statically typed programming language designed for the Common Language Infrastructure (CLI), targeting the .NET and Mono runtimes, enabling seamless interoperability with other .NET languages such as C# and VB.NET.[3][7] It supports type inference, allowing the compiler to automatically deduce variable types without explicit declarations in many cases, which enhances code readability while maintaining compile-time type safety.[8] Despite its static typing foundation, Boo incorporates optional duck typing, where objects are treated based on their capabilities rather than declared types, providing flexibility akin to dynamic languages.[9] 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.[6] Key traits include a clean, indentation-based syntax inspired by Python, eliminating the need for brackets or semicolons, which promotes concise and readable code.[3] Additional features encompass first-class functions, closures, generators, and an extensible compiler pipeline that allows users to introduce custom keywords or code transformations during compilation.[8] This extensibility makes Boo particularly suitable for metaprogramming and domain-specific language (DSL) creation within the .NET ecosystem.[9] 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.[3] Its Python-like readability facilitates adoption by developers familiar with scripting languages while benefiting from .NET's robust tooling and performance.[7] Released under the BSD 3-Clause open-source license, Boo encourages community contributions and commercial use without restrictive terms.[6]Design philosophy
Boo's design philosophy centers on creating a "wrist-friendly" syntax that minimizes boilerplate code and enhances developer productivity, drawing directly from the language's founding manifesto which emphasizes clean, readable code inspired by Python's elegance.[6] This approach eliminates unnecessary keywords, brackets, and semicolons in favor of Python-style indentation and automatic type inference, allowing developers to focus on logic rather than syntactic overhead.[3] The manifesto 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 syntactic sugar for common patterns like list literals and object initializers.[6] 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.[3] 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.[1] 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 duck typing for greater flexibility, albeit at a runtime cost similar to IronPython.[3] This hybrid model ensures type safety without rigid enforcement, supporting safe runtime casting where feasible.[1] 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.[3] This bridges the gap between Python's expressiveness and .NET's infrastructure, fostering productivity without compromising on platform strengths.[6]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.[10] 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 Unicode, globalization, and web services.[11] 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.[10] The first public release of Boo occurred in 2004, announced through the project's new website and discussed in programming communities as a novel CLR-based language with optional typing and an open compilation pipeline.[12] 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.[10] From the outset, the language 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 metaprogramming without sacrificing readability.[10] In a 2004 manifesto authored by Oliveira, Boo was positioned as a language balancing simplicity—through Python-inspired syntax, automatic type inference, and minimal boilerplate—with power via first-class functions, generators, and syntactic sugar for common patterns.[10] 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 Java.[11] 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.[13] 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.[14] 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.[15] 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.[16] Yes. Also, official resource threads and tutorials were maintained to support Boo usage.[17] 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
Unity Technologies discontinued support for Boo as a scripting language in Unity 4.5, released in 2014, in favor of prioritizing C# development, with the Boo compiler fully removed from the engine in Unity 2018 LTS.[18][5] 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 GitHub repository, where he remains listed among key maintainers.[6] The last official stable release, version 0.9.7, was issued on March 25, 2013. GitHub activity has been minimal since 2019, with the most recent commit—a minor update to a community link—occurring in 2021, indicating stalled core development.[19] As of 2025, 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 GitHub, primarily for niche maintenance or integration experiments, but no significant revival efforts have emerged.[6]Influences and ecosystem
Inspirations from other languages
Boo's design draws significant inspiration from Python, particularly in its emphasis on readability and clean syntax. The language 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 readability, as articulated in its official documentation, allowing developers to focus on logic rather than boilerplate.[3][4] Complementing Python's dynamic influences, Boo is heavily shaped by C#, leveraging the .NET Common Language Infrastructure for seamless integration and performance. This includes adopting C#'s object-oriented paradigms, such as classes, inheritance, and interfaces, to support robust, type-safe development within the .NET ecosystem. Boo's static typing, with optional type inference, 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.[3][4] 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 rapid prototyping alongside C#-level optimization for production use, distinguishing it as a versatile tool for .NET developers seeking dynamic flair in a statically typed environment.[3][4]Related tools and integrations
The Boo Language Compiler, known asbooc, compiles Boo source code into Intermediate Language (IL) assemblies compatible with the .NET Framework and Mono runtime environments.[8] 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.[20]
Boo benefits from integration with several integrated development environments (IDEs) within the .NET ecosystem. SharpDevelop provides full support for Boo through a dedicated add-in, including features like syntax highlighting, refactoring, code completion, and a forms designer.[21] MonoDevelop, 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 debugging and project management.[22] Its successor, Xamarin Studio (later integrated into Visual Studio for Mac), inherited this support but with diminishing updates as focus shifted to C#-centric mobile development.[23] For Microsoft Visual Studio, support is limited to community-developed plugins, such as the Visual Boo extension for versions 2017 and 2019, which offers basic project creation, syntax highlighting, and IntelliSense but lacks the depth of native integration.[24]
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.[3] 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.[5]
Boo has influenced subsequent projects in the open-source ecosystem, particularly the Genie 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 GObject integration.[25] Similarly, Vala, a language for GNOME 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 syntax highlighting and visualizing the Abstract Syntax Tree (AST) to aid in debugging and metaprogramming experimentation.[26]
Language features
Type system and inference
Boo employs a static type system that performs checks at compile time to ensure type safety, drawing on the Common Language Infrastructure (CLI) of .NET for its foundational semantics.[2][9] This approach allows developers to catch type-related errors early, similar to languages like C#, while incorporating mechanisms for greater flexibility. Local type inference enables the omission of explicit type declarations in many cases; for instance, assigning a value such as an integer literal automatically infers the appropriate type, likeint, without requiring manual specification.[2][27] This inference 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.[9]
A key feature supporting flexibility within this static framework is duck typing, which allows objects to be accepted based on the presence of required methods and properties rather than strict inheritance or nominal typing. To enable duck typing, 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.[9][27][28] This optional dynamic behavior 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 compiler performs thorough type checks, but the duck typing option provides a bridge to more dynamic styles, influenced briefly by Python's emphasis on runtime adaptability.[3][9]
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.[2] Reference types, like classes and interfaces, are allocated on the heap and passed by reference, 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.[2] Generics extend this by permitting parameterized types, such as generic lists, which the compiler resolves at compile time for optimal performance on the CLI.[8] This combination ensures a cohesive object-oriented model while leveraging inference and optional duck typing for expressive, safe programming.[9]
Metaprogramming capabilities
Boo provides robust metaprogramming facilities centered on compile-time code generation and transformation, enabling developers to extend the language's syntax and behavior without runtime overhead.[8] These capabilities are exclusively compile-time, ensuring that metaprogrammed code compiles to efficient .NET assemblies without introducing dynamic introspection costs.[8]Macros
Boo supports Lisp-inspired hygienic macros that allow for the definition of custom syntax and keywords, facilitating domain-specific language creation and code reuse.[29] Macros are implemented by creating classes that conform to theBoo.Lang.Compiler.IAstMacro interface, where the Expand method transforms an abstract syntax tree (AST) node into equivalent Boo code during compilation.[29] 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.[29]
For instance, a with macro can simplify repetitive object member access by wrapping statements in a block tied to an instance:
with fooInstanceWithReallyLongName:
_f1 = 100
_DoSomething()
with fooInstanceWithReallyLongName:
_f1 = 100
_DoSomething()
fooInstanceWithReallyLongName.f1 = 100
fooInstanceWithReallyLongName.DoSomething()
fooInstanceWithReallyLongName.f1 = 100
fooInstanceWithReallyLongName.DoSomething()
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
Extensible Compiler
The Boo compiler features a modular pipeline that permits injection of custom steps for AST transformations, supporting aspect-oriented programming (AOP) techniques such as code weaving.[30] Developers can hook into various compilation stages to rewrite code, for example, automatically inserting logging statements around method calls without altering source files.[8] 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.[30][27] An AOP example might use an attribute to weave logging into methods, transforming:[LogAttribute]
def ProcessData(data):
return data * 2
[LogAttribute]
def ProcessData(data):
return data * 2
Multimethods
Boo implements multimethods, also known as multiple dispatch, where method selection occurs at runtime based on the actual types of all arguments, enabling advanced polymorphic behavior beyond single-dispatch systems.[10] This is realized through duck typing, allowing overloads to be resolved dynamically without requiring explicit type hierarchies.[31] A static multimethod example for pretty-printing expressions demonstrates dispatch on argument types: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)
prettyPrint(AddExp(e1: IntExp(3), e2: IntExp(4))) outputs 3 + 4, selecting the AddExp overload based on runtime type.[31] Instance methods can similarly dispatch on collections of mixed types, such as summing integers while handling lists recursively.[31] This feature promotes flexible, type-agnostic code that adapts to varying inputs.[10]
Functional and advanced constructs
Boo supports functional programming 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: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!
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()
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
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:
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
for loops or enumerable methods, integrating with Boo's collection handling.[27]
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:
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]
=~ 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:
text = "Hello, Boo!"
if text =~ /Boo/:
print("Match found") # Outputs: Match found
text = "Hello, Boo!"
if text =~ /Boo/:
print("Match found") # Outputs: Match found
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:
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")
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
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.[36][37] The simplest Boo program, a "Hello, World!" example, demonstrates this minimalism:print "Hello, World!"
print "Hello, World!"
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).[36][37]
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.[38]
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 boolean 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:
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)
$ prefix within double-quoted strings, avoiding concatenation. 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.[38][37]
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:
def greet():
print "Hello from Boo!"
greet()
def greet():
print "Hello from Boo!"
greet()
Control flow and structures
Boo provides a suite of control flow mechanisms inspired by Python's indentation-based structure, emphasizing readability and conciseness. Conditional statements include the standardif construct, which executes a block of code if a Boolean expression 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.[40]
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.[41][42]
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.[42]
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 memory efficiency in data processing tasks.[4]
Object-oriented syntax
Boo employs a clean, indentation-based syntax for defining classes, drawing inspiration from Python while integrating seamlessly with the .NET Common Language Runtime (CLR). A class is declared using theclass 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:
class Cat:
def constructor():
pass
class Cat:
def constructor():
pass
Cat with an optional constructor invoked during instantiation, such as fluffy = Cat().[43]
Inheritance in Boo supports both single and multiple inheritance through interfaces, promoting code reuse and polymorphism within the .NET ecosystem. Single inheritance 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. Multiple inheritance is achieved by implementing multiple interfaces, prefixed with I by convention, which define contracts without implementation. An example of single inheritance is:
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
Cat inherits from Feline and adds its own property. For multiple interfaces:
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
get and set blocks or via the [Property] attribute for automatic backing field generation. Explicit properties offer flexibility for validation or computation:
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()
class Cat:
[Property(Name)]
_name as string
class Cat:
[Property(Name)]
_name as string
cat.Name = "Fluffy", and Boo infers the type from the backing field where applicable. Read-only properties omit the set block, enhancing data integrity.[44][43]
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:
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)
publisher.OnChange += handler. This syntax supports add/remove accessors for custom event logic if needed, ensuring thread-safe notifications in multi-threaded .NET applications.[6]
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:
import [System](/page/System)
Console.WriteLine("Hello, Boo!")
import [System](/page/System)
Console.WriteLine("Hello, Boo!")
from clauses are used:
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()
mscorlib and System, but explicit imports are required for external libraries, promoting modular design and avoiding namespace pollution.[45]