All 7 entries tagged Nemerle

No other Warwick Blogs use the tag Nemerle on entries | View entries tagged Nemerle at Technorati | There are no images tagged Nemerle on this blog

March 14, 2007

Overriding implementation class members

Follow-up to Implementation Classes Again from codeMonkey.Weblog();

On the way home I thought of a way to override implementation class members in the user class.

class User
  use SomeImpl for IFooBar

  [OverrideImpl(IFooBar)] private SomeMethod() : void
    // specialized code...

class SomeImpl : IFooBar
  public virtual SomeMethod() : void
    // Normal code

The macro can translate this into “real” code by creating a new class inside User that inherits from the implementation class. We override the virtual method and make call to the User method.

The partial expansion then looks like this:

class User
  use SomeImpl_User_Overrides for IFooBar

  private SomeMethod() : void
    // Specialized code

  class SomeImpl_User_Overrides : SomeImpl
    private _user : User
    public this(user : User)
      _user = user

    public override SomeMethod()

So then we use the specialized class as the implementation.

This approach will also work for abstract methods defined in the implementation class that require implementation.

Implementation Classes Again

I’ve been thinking more about traits and implementation classes in OOP.
I put together a quick program in Nemerle to demonstrate the ideas I’m playing with.

I defined a class that implements System.ComponentModel.IEditableObject. It takes a “user” object as a parameter and implements a simple stack based state saver. BeginEdit copies all the fields of the user, pushing them onto the stack. CancelEdit can then restore state by popping the stack and setting the fields back to those saved values. EndEdit simply pops the stack leaving the current values in place.

    class EditableObject[T] : IEditableObject
        private _states : Stack[Dictionary[FieldInfo, object]] = Stack()
        private _user : T

        // We only take the reflection performance hit once per type T.
        private static _fields : array[FieldInfo]
        static this()
            _fields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)

        public this(user : T)
            _user = user

        public BeginEdit() : void

        public EndEdit() : void
            if (_states.Count > 0)
                _ = _states.Pop() // Discard top of stack
                throw InvalidOperationException()

        public CancelEdit() : void
            if (_states.Count > 0)
                throw InvalidOperationException()

        private CopyState() : Dictionary[FieldInfo, object]
            def dictionary = Dictionary()
            foreach (f in _fields)
                dictionary[f] = f.GetValue(_user)

        private RestoreState(previous : Dictionary[FieldInfo, object]) : void
            foreach (f in _fields)
                f.SetValue(_user, previous[f])

I now want to use this “implementation” class in many different classes. I do not want to inherit from this class directly. Trying to create an abstract base class purely to stuff lots of different implementation details together is just plain ugly too.
So I used the Nemerle ProxyPublicMembers macro.

    class Person : IEditableObject
        [ProxyPublicMembers] _editable : EditableObject[Person] = EditableObject(this)

        [Accessor(flags=WantSetter)] mutable _firstName : string
        [Accessor(flags=WantSetter)] mutable _surname : string

        public this(firstName : string, surname : string)
            _firstName = firstName
            _surname = surname

        public override ToString() : string
            $"$FirstName $Surname"

With the single line:
[ProxyPublicMembers] _editable : EditableObject[Person] = EditableObject(this)
the three public methods BeginEdit, CancelEdit, EndEdit are inserted into Person and they simply call the respective methods on the _editable instance field.

A simple test of the code is:

    static class Program
        static Main() : void
            def p1 = Person("Andrew", "Davey")

            p1.FirstName = "Foo" 

            p1.Surname = "Smith" 


Andrew Davey
Foo Davey
Andrew Davey
Andrew Smith

One of the advantages of this implementation class approach is the ability to store both instance and static state. The EditableObject only takes the reflection performance hit to get a type’s fields once. The user class never has to know about this state at all.

It would also be possible to enable a form of “overriding” by the user class. Perhaps it needs a special way to save and restore state. We just need a way to tell the implementation class to call the user to do something, rather than doing it itself. Delegates could be passed to the implementation class upon construction. Or perhaps a more declarative approach could be taken by marking “override” methods in a user class with an attribute.

[OverrideImplementation(EditableObject)] private CopyState() : Dictionary[FieldInfo, object]
  // do stuff here

We would just require some macro trickery to get this working I reckon.

As it stands the standard ProxyPublicMethods macro in Nemerle enables an excellent approach to modelling problems in clean OO style. I think an additional macro to tidy up the syntax would make things even nicer.

class Person
  uses EditableObject for IEditableObject


March 02, 2007

Multiple Interface Implementation via Proxy

Nemerle is like C# in that it only has single implementation inheritance and multiple interface inheritance. However when modelling business problems it would be beneficial to have multiple implementation inheritance to allow for better code reuse and modularisation.
For example, consider a PurchaseOrder object. We would like to add rich UI data binding functionality and undo/redo operations to it. The .NET framework contains a number of interfaces that should be implemented to achieve these goals. IEditableObject has methods BeginEdit, EndEdit and CancelEdit. INotifyPropertyChanged has an event PropertyChanged. The implementation of these is fairly standard so we do not want to write it in each class. In C#, we would usually make some kind of abstract base class that implements the interfaces and then inherit our real business classes from that.
Whilst this approach is fine for simple object models, things get a lot more difficult when not all business classes require all interfaces. Maybe some are read-only; maybe others have special auditing requirements. We end up creating many strange abstract base classes that implement different subsets of functionality. This inevitably leads to repeated code and a maintenance nightmare.
If we step back, we realise that we are actually abusing inheritance as an attempt to reduce code repetition. A better approach would be to have implementations of single interfaces as single classes that are then pulled together by the actual business classes. The business classes are then in charge of what implementations they require, rather than relying on a rather fragile base class.
The following Nemerle code demonstrates how this might work:

class PurchaseOrder : IEditableObject
    private _editableObject : IEditableObject
    public this()
        _editableObject = EditableObjectImplementation(this)
    public BeginEdit() : void
    public EndEdit() : void
    public CancelEdit() : void

The constructor creates and instance of some implementation class. Any calls to the interfaces methods are forwarded to the implementation class. Note that we provide the implementation class with the object that is using it. This allows the implementation class to do things like reflection to get all the private state to be saved.
Basically, we are implementing a form of the Proxy design pattern.
The above idea will work fine (even in C# and VB.NET), however it requires lots of “glue” code to be written. This is where Nemerle macros come in handy!
Imagine being able to write something like:

class PurchaseOrder \
    use EditableObjectImplemenation for IEditableObject \
    use NotifyPropChangedImpl for INotifyPropertyChanged
// Look! No glue code at all now!

The “use” macro would expand out to code that includes private instance fields and the glue code that calls those instances.
Of course, the macros have to be quite smart, but there are already working Proxy macros for Nemerle that just need enhancing to support events (they already do properties and methods I believe).
Other enhancements allow an implementation class to place demands on the class using it. An implementation of some interface ICircle could provide members like “Area”, “Circumference” and “Diameter” but require the using class to have a member “Radius”. The implementation class calls back into the using class to get Radius. It can then provide the various additional members using that value. This idea follows from the work done on Traits in OOP, the difference here is that implementation are not mixed into the using class at compile time. By keeping them outside, they can do useful things like have their own state.

The benefits of such infrastructure are:
  • Classes are more logically decomposed.
  • Classes are less fragile.
  • Maintenance is easier.
  • Testing business classes by providing stub implementation is easy.

November 01, 2006

Nemerle, NUnit and custom operators

Nemerle allows the definition of new operators. I always feel annoyed having to write code like “Assert.AreEqual(42, myVal)” when unit testing with NUnit.

So I created this operator for use in my project’s test library:

namespace Equin.Vectorization.Library.Tests
    module Utilities
        public static @=!=[T](x : T, y : T) : void
            Assert.AreEqual(x, y)

Now in my test cases I can use it like this:

[Test] public PixelAtTopLeft() : void
    using (bmp = CreateBitmap(Size(10, 10), [Pt(0,0)]))
        def ps = PixelSelector(bmp, Color.Black)
        def pixels = ps.GetPixels()

        mutable count = 0
        mutable aPoint : Pt[int] = null
        foreach (pt in pixels)
            aPoint = pt

        1 =!= count
        0 =!= aPoint.X
        0 =!= aPoint.Y

It’s just sugar, I know, but it makes the assertions really jump out at me. It’s less to type as well :)
I could even make it a macro instead of a method call, that would then let me create a pretty message string as well…

October 07, 2006

Nemerle VSIP

I am planning to write my project’s code using Nemerle . It has a good cross section of language features that I will leverage. The concentration on efficient algorithms and data structures will leverage the functional aspects of Nemerle. Whilst the vast .NET libraries and imperative constructs will make image handling and UI code easy.

Of course, being a Visual Studio junkie means I will require decent tool support. Luckily I managed to get the Nemerle VSIP (Visual Studio Integration Package) to work yesterday. Now I can edit code inside Visual Studio with the aid of intellisense, syntax highlighting and built-in compiler support.
The package is still somewhat under development, so I’m not sure how stable it will be. My project will not require too much code so I think it will hold up OK. To be honest, just having a Visual Studio “project” to manage building source, etc is a God send compared to manually writing build scripts and command line compiling!

I’m looking forward to getting this project off the ground. My current goal is writing the proposal document by week 3…

October 01, 2006

Circular, doubly–linked list

Follow-up to Loopy linked lists from codeMonkey.Weblog();

After taking considerable inspiration from a Haskell implementation , I managed to write some Nemerle code that creates a circular, doubly-linked list, without using any mutable variables.
It is not as elegant as the Haskell version because I had to use class fields to get lazy access to variables not yet assigned. Translating lines like:

mkDList xs = let (first,last) = go last xs first
             in  first

into Nemerle is tricky, even with the “lazy” macro.

So here’s the code…

#pragma indent

using System
using Nemerle

[Record] struct Node[T]
    public Prev : LazyValue[Node[T]]
    public Value : T
    public Next : LazyValue[Node[T]]

class LoopList[T]
    private first : Node[T]
    private last : Node[T]

    private this(items : list[T])
        def go = Go(lazy(last), items, lazy(first))
        (first,last) = (, go.last)

    private class Go
        private rest : LazyValue[Node[T]]
        public me : LazyValue[Node[T]]
        public last : LazyValue[Node[T]]

        public this(prev : LazyValue[Node[T]], items : list[T], next : LazyValue[Node[T]])
            match((prev, items, next))
                | (prev, [], next) =>
                    (me, last) = (next, prev)

                | (prev, x::xs, next) =>
                    me = lazy(Node(prev, x, rest))
                    def go = Go(me, xs, next)
                    (rest, last) = (, go.last)

    public static Create(xs : list[T]) : Node[T]

// Test Code

mutable n = LoopList.Create([1,2,3,4])

    Console.Write($"$(n.Value) ")
    n = n.Next

n = n.Prev
Console.WriteLine("and back again")
    Console.Write($"$(n.Value) ")
    n = n.Prev

// Output
1 2 3 4 1 2 3 4 1 2
and back again
2 1 4 3 2 1 4 3 2 1

I’m planning to use this in my 3rd year project. The Weiler-Atherton algorithm requires a CDDL.

August 06, 2006

Loopy linked lists

I've been playing with Nemerle today. It's a functional/OO hybrid for the .NET CLR. I needed a circular linked list for a project I'm working on. Basically a linked list where the end points back to the start.
Whilst Nemerle allows mutable variables, I felt dirty leaving all the beauty of "no side effects" programming behind. Luckily Nemerle allows lazy evaluation using some macro magic behind the scenes (That's right Dan, I said the "L" word ;)). This meant I could reference the first item effectively inside its own definition. (The laziness is not exactly first class like in Haskell, but it certainly works for me here.)
#pragma indent

using System
using Nemerle

class LoopList[T]
private first : LazyValue[LoopListItem[T]]

public this(values : list [T])
def build(xs)
| [] => first
| head::tail => lazy( LoopListItem(head, build(tail)) )
first = build(values)

public First : LoopListItem[T]

[Record] struct LoopListItem[T]
public Value : T
public Next : LazyValue[LoopListItem[T]]

// Test code:
mutable item = LoopList([1,2,3]).First

Console.Write($"$(item.Value) ")
item = item.Next

// Outputs:
// 1 2 3 1 2 3 1 2 3 1
Next I need to figure out a circular doubly linked list…

Google Ads

Search this blog

Most recent comments

  • I scratched my eye while i was holding some kind of plastic packaging.. Anyways the corner of the pl… by Ercan on this entry
  • About a year ago my contacts that i was wearing, i guess were fautly, because shortly after they wer… by Jon on this entry
  • I got shower gel in my eye 4 and a half days ago, and becasue i rubbed my eyes a lot, i have scratch… by Chris on this entry
  • This website may help–health/tc/Eye–Injuries–Home–Treatment by S on this entry
  • I somehow got dirt, or debris in my eye. The terrible pain sent me in a tailspin. I was afraid of sa… by Bobbi on this entry


August 2017

Mo Tu We Th Fr Sa Su
Jul |  Today  |
   1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31         


Blog archive

RSS2.0 Atom
Not signed in
Sign in

Powered by BlogBuilder