Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active December 7, 2017 02:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Porges/ea348cb5eb149afb1c31178b33f38faa to your computer and use it in GitHub Desktop.
Save Porges/ea348cb5eb149afb1c31178b33f38faa to your computer and use it in GitHub Desktop.
void Main()
{
var digits = Digits.Create("093884765");
var digitsOfLength3 = Digits3.Create("007");
Console.WriteLine($"digits: [{digits}] digitsOfLength3: [{digitsOfLength3}]");
}
static class DigitsDef
{
private static readonly Regex regex = new Regex("^[0-9]+$");
private static string VerifyDigits(int config, string value)
{
if (regex.IsMatch(value.Trim()) &&
(config == 0 || value.Length == config))
{
return value;
}
return null;
}
public class DigitsValidator : Cctor<int, string, string>
{ public DigitsValidator(int config) : base(config, VerifyDigits) { } }
public class ValidDigits : DigitsValidator
{ public ValidDigits() : base(0) {} }
public class ValidDigits2 : DigitsValidator
{ public ValidDigits2() : base(2) { } }
public class ValidDigits3 : DigitsValidator
{ public ValidDigits3() : base(3) { } }
public class ValidDigits4 : DigitsValidator
{ public ValidDigits4() : base(4) { } }
}
class Digits : DependentType<DigitsDef.ValidDigits, int, string, string> { private Digits() {} }
class Digits2 : DependentType<DigitsDef.ValidDigits2, int, string, string> { private Digits2() {} }
class Digits3 : DependentType<DigitsDef.ValidDigits3, int, string, string> { private Digits3() {} }
class Digits4 : DependentType<DigitsDef.ValidDigits4, int, string, string> { private Digits4() {} }
class Cctor<Config, T, T2>
{
private Config _config;
private Func<Config, T, T2> _vfn;
public Cctor(Config config, Func<Config, T, T2> vfn)
{
_config = config;
_vfn = vfn;
}
public T2 TryCreate(T input) => _vfn(_config, input);
}
class DependentType<Cctor, Config, T, T2>
where Cctor : Cctor<Config, T, T2>, new()
{
T2 _value;
protected DependentType() => throw new NotSupportedException("Only derive to provide aliases");
private DependentType(T2 value) => _value = value;
public static DependentType<Cctor, Config, T, T2> Create(T input)
{
var result = new Cctor().TryCreate(input);
if (result != null)
{
return new DependentType<Cctor, Config, T, T2>(result);
}
return null;
}
public override string ToString() => _value.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment