fork(1) download
  1. using System;
  2.  
  3. public class Option {
  4. public static Option<T> None<T>() {
  5. return new Option<T>(default(T), present: false);
  6. }
  7.  
  8. public static Option<T> Some<T>(T value) {
  9. return new Option<T>(value, present: true);
  10. }
  11. }
  12.  
  13. public class Option<T> {
  14. private readonly T value;
  15. public bool Present { get; private set; }
  16.  
  17. internal Option(T value, bool present) {
  18. this.value = value;
  19. Present = present;
  20. }
  21.  
  22. public T Get() {
  23. if (!Present) {
  24. throw new Exception("you suck");
  25. }
  26. return value;
  27. }
  28.  
  29. public Option<U> Select<U>(Func<T, U> f) {
  30. if (Present) {
  31. return Option.Some<U>(f(value));
  32. } else {
  33. return Option.None<U>();
  34. }
  35. }
  36.  
  37. public override string ToString() {
  38. if (Present) {
  39. return "Some(" + value.ToString() + ")";
  40. } else {
  41. return "None";
  42. }
  43. }
  44. }
  45.  
  46. public static class Program {
  47. public static void Main() {
  48. Console.WriteLine(Option.Some("hello").Select(x => x.Length));
  49. Console.WriteLine(Option.None<string>().Select(x => x.Length));
  50. }
  51. }
Success #stdin #stdout 0.03s 33880KB
stdin
Standard input is empty
stdout
Some(5)
None