2bam

Immutable list for C#

Sep 12th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class FList<T> : IEnumerable<T> {
  6.     readonly IEnumerable<T> collection;
  7.        
  8.     public FList() {
  9.         collection = new T[0];
  10.     }
  11.  
  12.     public FList(T singleValue) {
  13.         collection = new T[1] { singleValue };
  14.     }
  15.        
  16.     public FList(IEnumerable<T> collection) {
  17.         this.collection = collection;
  18.     }
  19.  
  20.     //Specificity to resolve ambiguity between FList-IEnumerable
  21.     public static FList<T> operator+(FList<T> lhs, FList<T> rhs) {
  22.         return FList.New(lhs.collection.Concat(rhs.collection));
  23.     }
  24.  
  25.     public static FList<T> operator+(FList<T> lhs, IEnumerable<T> rhs) {
  26.         return FList.New(lhs.collection.Concat(rhs));
  27.     }
  28.  
  29.     public static FList<T> operator+(IEnumerable<T> lhs, FList<T> rhs) {
  30.         return FList.New(FList.New(lhs).collection.Concat(rhs));
  31.     }
  32.  
  33.     //This isn't semantically correct, but it's cleaner to read.
  34.     public static FList<T> operator+(FList<T> lhs, T rhs) {
  35.         return lhs + FList.New(rhs);
  36.     }
  37.  
  38.     //This isn't semantically correct, but it's cleaner to read.
  39.     public static FList<T> operator+(T lhs, FList<T> rhs) {
  40.         return FList.New(lhs) + rhs;
  41.     }
  42.        
  43.     public IEnumerator<T> GetEnumerator() {
  44.         foreach(var element in collection)
  45.             yield return element;
  46.     }
  47.        
  48.     IEnumerator IEnumerable.GetEnumerator() {
  49.         return GetEnumerator();
  50.     }
  51. }
  52.  
  53. public static class FList {
  54.     static public FList<T> ToFList<T>(this IEnumerable<T> lhs) {
  55.         return New(lhs);
  56.     }
  57.  
  58.     static public FList<T> New<T>() {
  59.         return new FList<T>();
  60.     }
  61.  
  62.     static public FList<T> New<T>(T singleValue) {
  63.         return new FList<T>(singleValue);
  64.     }
  65.        
  66.     static public FList<T> New<T>(IEnumerable<T> collection) {
  67.         return new FList<T>(collection);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment