MapAlphabet.cs
84 lines
| 2.4 KiB
| text/x-csharp
|
CSharpLexer
cin
|
r163 | using System; | ||
using System.Collections.Generic; | ||||
using System.Linq; | ||||
namespace Implab.Automaton { | ||||
public class MapAlphabet<T> : IAlphabetBuilder<T> { | ||||
readonly Dictionary<T,int> m_map; | ||||
cin
|
r171 | int m_nextCls; | ||
readonly bool m_supportUnclassified; | ||||
cin
|
r164 | |||
cin
|
r171 | public MapAlphabet(bool supportUnclassified, IEqualityComparer<T> comparer) { | ||
m_map = comparer != null ? new Dictionary<T, int>(comparer) : new Dictionary<T,int>(); | ||||
m_supportUnclassified = supportUnclassified; | ||||
m_nextCls = supportUnclassified ? 1 : 0; | ||||
cin
|
r163 | } | ||
#region IAlphabetBuilder implementation | ||||
public int DefineSymbol(T symbol) { | ||||
int cls; | ||||
cin
|
r171 | return m_map.TryGetValue(symbol, out cls) ? cls : DefineSymbol(symbol, m_nextCls); | ||
} | ||||
cin
|
r163 | |||
cin
|
r171 | public int DefineSymbol(T symbol, int cls) { | ||
Safe.ArgumentAssert(cls >= 0, "cls"); | ||||
cin
|
r163 | |||
cin
|
r171 | m_nextCls = Math.Max(cls + 1, m_nextCls); | ||
cin
|
r163 | m_map.Add(symbol, cls); | ||
return cls; | ||||
} | ||||
public int DefineClass(IEnumerable<T> symbols) { | ||||
cin
|
r171 | return DefineClass(symbols, m_nextCls); | ||
} | ||||
public int DefineClass(IEnumerable<T> symbols, int cls) { | ||||
Safe.ArgumentAssert(cls >= 0, "cls"); | ||||
cin
|
r163 | Safe.ArgumentNotNull(symbols, "symbols"); | ||
cin
|
r171 | |||
m_nextCls = Math.Max(cls + 1, m_nextCls); | ||||
cin
|
r163 | |||
cin
|
r171 | foreach (var symbol in symbols) | ||
m_map[symbol] = cls; | ||||
return cls; | ||||
cin
|
r163 | } | ||
#endregion | ||||
#region IAlphabet implementation | ||||
cin
|
r171 | public int Translate(T symbol) { | ||
cin
|
r163 | int cls; | ||
cin
|
r171 | if (m_map.TryGetValue(symbol, out cls)) | ||
return cls; | ||||
if (!m_supportUnclassified) | ||||
throw new ArgumentOutOfRangeException("symbol", "The specified symbol isn't in the alphabet"); | ||||
cin
|
r178 | return AutomatonConst.UNCLASSIFIED_INPUT; | ||
cin
|
r163 | } | ||
public int Count { | ||||
get { | ||||
return m_nextCls; | ||||
} | ||||
} | ||||
cin
|
r171 | public bool Contains(T symbol) { | ||
return m_supportUnclassified || m_map.ContainsKey(symbol); | ||||
} | ||||
cin
|
r172 | |||
public IEnumerable<T> GetSymbols(int cls) { | ||||
cin
|
r181 | Safe.ArgumentAssert(!m_supportUnclassified || cls > 0, "cls"); | ||
cin
|
r172 | return m_map.Where(p => p.Value == cls).Select(p => p.Key); | ||
} | ||||
cin
|
r163 | #endregion | ||
cin
|
r176 | |||
public IEnumerable<KeyValuePair<T,int>> Mappings { | ||||
get { | ||||
return m_map; | ||||
} | ||||
} | ||||
cin
|
r163 | } | ||
} | ||||