Magik (programming language)

Magik (programming language)

Magik is an object-oriented programming language that supports multiple inheritance, polymorphism and is dynamically typed. It is provided by GE Energy as part of its Smallworld technology platform and was designed from the outset to implement complex applications for enterprise utilities such as power distribution and telecommunications.

Magik (Inspirational Magik) was originally introduced in 1990 and has been improved and updated over the years. Its current version is 4.0 or Magik SF (Small Footprint).

Contents

Similarities with Smalltalk

Magik itself shares some similarities with Smalltalk in terms of its language features and its architecture: the Magik language is compiled into byte codes interpreted by the Magik virtual machine. The Magik virtual machine is available on several platforms including Microsoft Windows, various flavours of Unix and Linux.

Magik is console based and code can be modified on the fly even when an application is running. The console can also be used to execute Magik code and to see the results.

Compiled code is stored in a single file called an image file. Each image file holds the compiled byte-codes and the state of the session (for example variable values) when the image was last saved.

Language features

Comments

Magik uses the # token to mark sections of code as comments:

 # This is a comment.
Assignments

Magik uses the << operator to make assignments:

 a << 1.234
 b << b + a
 c << "foo" + "bar" # Concat strings

For clarity, this notation is read as "A becomes 1.234" or "b becomes b plus a". This terminology separates assignment from comparison.

Magik also supports a compressed variation of this operator that works in a similar way to those found in C:

 b +<< a # Equivalent to b << b + a

To print a variable you can use the following command

 a << "hello"
 write(a)
Symbols

As well as conventional data types such as integers, floats and strings Magik also implements symbols. Symbols are a special token data type that are used extensively throughout Magik to uniquely identify objects. They are represented by a colon followed by a string of characters. Symbols can be escaped using the vertical bar character. For example:

 a << :hello  # whenever :hello is encountered, it is the same instance
 b << :|hello world|
Dynamic typing

Magik variables are not typed as they are in say C# and can reference different objects at runtime. Everything in Magik is an object (there is no distinction between objects and primitive types such as integers):

 a << 1.2     # a floating point number is assigned to variable 'a'
 a << "1.2"   # later, a string is assigned to variable 'a'
Objects

Objects are implemented in Magik using exemplars. Exemplars have similarities to classes in other programming languages such as Java, but with important differences. Magik supports multiple inheritance, and mixins (which implement functionality with no data). New instances are made by cloning an existing instance (which will typically be the exemplar but does not have to be).

New exemplars are created using the statement def_slotted_exemplar(), for example:

 def_slotted_exemplar(:my_object,
 {
   {:slot_a, 34},
   {:slot_b, "hello"}
 }, {:parent_object_a, :parent_object_b})

This code fragment will define a new exemplar called my_object that has two slots (or fields) called slot_a (pre-initialized to 34) and slot_b (pre-initialised to "hello") that inherits from two existing exemplars called parent_object_a and parent_object_b.

Comparison

Magik implements all usual logical operators (=, <, <=, >, >=, ~=/<>) for comparison, as well as a few unusual ones. The _is and _isnt operators are used for comparing specific instances of objects, or object references rather than values.

For example:

 a << "hello"
 b << "hello"
 a = b returns True (_true) because the values of a and b are equal
 a _is b returns False (_false) because a is not the same instance as b
 a << "hello"
 b << a = b returns True (_true) because the values of a and b are equal
 a _is b returns True (_true) because b was assigned the specific instance of the same object as a, rather than the value of a.
Methods

Methods are defined on exemplars using the statements _method and _endmethod:

 _method my_object.my_method(a, b)
   _return a + b
 _endmethod

It is convention to supply two methods new() (to create a new instance) and init() (to initialize an instance).

 # New method
 _method person.new(name, age)
   _return _clone.init(name, age)
 _endmethod
 # Initialize method.
 _private _method person.init(name, age)
    # Call the parent implementation.
    _super.init(name, age)
    # Initialise the slots.
    .name << name
    .age << age
   _return _self
 _endmethod

The _clone creates a physical copy of the person object. The _super statement allows objects to invoke an implementation of a method on the parent exemplar. Objects can reference themselves using the _self statement. An object's slots are accessed and assigned using a dot notation.

Methods that are not part of the public interface of the object can be marked private using the _private statement. Private methods can only be called by _self, _super and _clone.

Optional arguments can be declared using the _optional statement. Optional arguments that are not passed are assigned by Magik to the special object _unset (the equivalent of null). The _gather statement can be used to declare a list of optional arguments.

 _method my_object.my_method(_gather values)     
 _endmethod
Iteration

In Magik the _for, _over, _loop and _endloop statements allow iteration.

 _method my_object.my_method(_gather values)
   total << 0.0
   _for a _over values.elements()
   _loop
      total +<< a
   _endloop
   _return total
 _endmethod
 m << my_object.new()
 x << m.my_method(1.0, 2, 3.0, 4) # x = 10.0

Here values.elements() is an iterator which helps to iterate the values.

In Magik generator methods are called iterator methods. New iterator methods can be defined using the _iter and _loopbody statements:

 _iter _method my_object.even_elements()
   _for a _over _self.elements()
   _loop
     _if a.even? _is _true
     _then
        _loopbody(a)       
     _endif
   _endloop
 _endmethod
Procedures

Magik also supports functions called procedures. Procedures are also objects and are declared using the _proc and _endproc statements. Procedures are assigned to variables which may then be invoked:

 my_procedure << _proc @my_procedure(a, b, c)
   _return a + b + c
 _endproc
 x << my_procedure(1, 2, 3) # x = 6
Language Quirks

Because Magik was originally developed in England, methods in the core smallworld libraries are spelled using British English. For example:

  Use "initialise", not "initialize".
Collections

Like other programming language Magik too has collections. They include the following:

  • Simple Vector
  • Rope
  • Hash Table
  • Property List
  • Equality set
  • Bags

Hello World example

The following is an example of the Hello world program written in Magik:

 write ("Hello World!")

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • Magik — is an alternative spelling of magic , and can refer to: Magik (programming language) Magik (comics), an alias also used by Marvel Comics character Illyana Rasputin (and also by Amanda Sefton) Magik (rapper), a Polish rapper Magik (Illyana and… …   Wikipedia

  • List of programming languages — Programming language lists Alphabetical Categorical Chronological Generational The aim of this list of programming languages is to include all notable programming languages in existence, both those in current use and historical ones, in… …   Wikipedia

  • Smallworld GIS — Das Smallworld Geoinformationssystem ist ein Geoinformationssystem, ein Datenbanksystem zur Verwaltung von geografischen und topologischen Informationen. Das Smallworld GIS basiert auf einem 1989 von Richard ‚Dick’ Newell verfassten Papier mit 10 …   Deutsch Wikipedia

  • Smallworld — Systems Ltd est une société d édition de système d information géographique (SIG) créé à Cambridge, Royaume Uni, en 1988 par Dick Newell, Tim Cadman, Richard Green, David Theriault, Mike Williamson, Hugh Fingland, Arthur Chance, Mark Easterfield …   Wikipédia en Français

  • Land Allocation Decision Support System — LADSS or Land Allocation Decision Support System, is an agricultural land use planning tool being developed at The Macaulay Institute. LADSS is implemented using the programming language G2 from Gensym alongside a Smallworld GIS application using …   Wikipedia

  • Assignment (computer science) — In computer programming, an assignment statement sets or re sets the value stored in the storage location(s) denoted by a variable name. In most imperative computer programming languages, assignment statements are one of the basic statements.… …   Wikipedia

  • Список языков программирования — Списки языков программирования Алфавитный По категориям Хронологический Генеалогический Цель этого алфавитного списка языков программирования состоит в том, чтобы дать полный перечень всех существующих языков программирования, как используемых в… …   Википедия

  • Liste des langages de programmation — Le but de cette Liste des langages de programmation est d inclure tous les langages de programmation existants, qu ils soient actuellement utilisés ou historiques, par ordre alphabétique. Ne sont pas listés ici les langages informatiques de… …   Wikipédia en Français

  • Magic — Contents 1 Computing 2 Gaming 3 Film 4 Music …   Wikipedia

  • Smallworld — was a GIS company founded in Cambridge, England, in 1989 by Dick Newell and others. It grew to become the global market leader for GIS in utilities and communications, according to Daratech. In September 2000, it was acquired by GE Energy, a… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”