Calling Other CLR-Hosted Languages


The discussion so far has centered on how various functional-language features can be adapted in such a way that data and functions can be easily accessed from other CLR-hosted languages. This is only one half of the picture ”functional-language programmers also need to be able to access code written in other languages.

The fundamental issue in this case is independent of the CLR and the .NET Framework. Functional languages are "stateless" (no updateable variables ), while object-oriented languages are fundamentally about state ”the prototypical "object" encapsulates some state (its instance variables) and provides access to it via its methods .

Fortunately, this issue has been well researched, as it is essentially the same issue as supporting I/O, and a language with no I/O would be useless! A number of successful I/O techniques have been developed over the years , including continuations [12] and monads [6], the latter having now been adopted as standard in Haskell. To a functional language, calling a method in an object-oriented language is just the same as performing an I/O operation [13].

Following Haskell, Mondrian uses monadic I/O. The standard "Hello" program may be written as follows :

 main : IO Void;  main = {  PutStr("Please enter you name: ");    name <- GetStr();    PutStr("Hello there " + name); } 

To support calling other languages CLR-hosted languages, which must by the nature of the CLR provide an object-oriented interface, we introduce two constructs in Mondrian:

  • create , which takes the specification of a class constructor and produces a monadic version of it,

  • invoke , which performs the same operation for methods

We explain these constructs by using examples. The simple program in Listing G.2 executes on the CLR and produces a single random number by calling the .NET Framework's System.Random .

Listing G.2
 // define a monadic constructor for System.Random dotnetRand : IO<System.Random>; dotnetRand = create System.Random(); // define a monadic interface to the Random.Next method nextRand : Integer -> System.Random -> IO<Integer>; nextRand = invoke System.Random.Next(Int32) main = {  gen <- dotNetRand;    num <- nextRand 10 gen;    putStrLn ("Random 1..10: " + show num); } 

This approach fits seamlessly into the monadic system, giving functional-language programmers access to other languages using a model with which they are familiar.



Programming in the .NET Environment
Programming in the .NET Environment
ISBN: 0201770180
EAN: 2147483647
Year: 2002
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net