[Nemerle] Constraints
От: Klapaucius  
Дата: 29.01.07 08:30
Оценка:
Имеется простой код на С#, который не удается повторить на Nemerle
    public interface ICalculator<T>
    {
        T Add(T a, T b);
    }

    public struct FloatCalculator : ICalculator<float>
    {
        public float Add(float a, float b)
        {
            return a + b;
        }
    }

    public struct DoubleCalculator : ICalculator<double>
    {
        public double Add(double a, double b)
        {
            return a + b;
        }
    }

    public struct Complex<T, C>
        where T : struct
        where C : struct, ICalculator<T>
    {
        static C calc = new C();
        
        T _re;
        public T Re { get { return _re; } }

        T _im;
        public T Im { get { return _im; } }

        public Complex(T re, T im)
        {
            _re = re;
            _im = im;
        }
                
        static public Complex<T, C> operator + (Complex<T, C> a, Complex<T, C> b) 
        {
            return new Complex<T, C>(calc.Add(a.Re, b.Re), calc.Add(a.Im, b.Im));
        }
    }


Казалось бы, все просто, однако есть одно но.
public interface ICalculator[T]
{
    Add(a : T, b : T) : T;
}

public struct FloatCalculator : ICalculator[float]
{
    public Add(a : float, b : float) : float
    {
        a + b
    }
}

public struct DoubleCalculator : ICalculator[double]
{
    public Add(a : double, b : double) : double
    {
        a + b
    }
}

namespace ComplexMath
{
    [Record]
    public struct Complex['t, 'c]
        where 't : struct // так можно
        where 'c : new(), ICalculator['t] // так тоже можно
                // where 'c : struct, ICalculator['t] - а так нельзя.
                // the type `'c.854' must be a value type in order to use 
                // it as type parameter `'c' in ComplexMath.Complex['t.853, 'c.854]
                // кстати, при задании двух и более констрейнтов для типа арности 2 и больше
                // январский CTP интеграции обнаруживает несуществующие ошибки.
                
    {
        static calc : 'c = 'c();
        
        [Accessor] mutable _re : 't;
        [Accessor] mutable _im : 't;
        
        static public @+ (a : Complex['t, 'c], b : Complex['t, 'c]) : Complex['t, 'c]
        {
            Complex.['t, 'c](calc.Add(a.Re, b.Re), calc.Add(a.Im, b.Im))
        }
    }
... << RSDN@Home 1.2.0 alpha rev. 655>>

30.01.07 17:49: Перенесено модератором из 'Декларативное программирование' — IT
'You may call it "nonsense" if you like, but I'VE heard nonsense, compared with which that would be as sensible as a dictionary!' (c) Lewis Carroll
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.