tstackproject.lpr 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Generic types for NewPascal.org and FPC!
  2. // Original version by keeper89.blogspot.com, 2011
  3. // FPC version by Maciej Izak (hnb), 2014
  4. program TStackProject;
  5. {$MODE DELPHI}
  6. {$APPTYPE CONSOLE}
  7. uses
  8. SysUtils,
  9. Generics.Collections;
  10. type
  11. // We will cook pancakes, put them on a plate and take the last
  12. TPancakeType = (ptMeat, ptCherry, ptCurds);
  13. TPancake = record
  14. strict private
  15. const
  16. PANCAKE_TYPE_NAMES: array [TPancakeType] of string =
  17. ('meat', 'cherry', 'curds');
  18. public
  19. var
  20. PancakeType: TPancakeType;
  21. class function Create(PancakeType: TPancakeType): TPancake; static;
  22. function ToString: string;
  23. end;
  24. class function TPancake.Create(PancakeType: TPancakeType): TPancake;
  25. begin
  26. Result.PancakeType := PancakeType;
  27. end;
  28. function TPancake.ToString: string;
  29. begin
  30. Result := Format('Pancake with %s', [PANCAKE_TYPE_NAMES[PancakeType]])
  31. end;
  32. var
  33. PancakesPlate: TStack<TPancake>;
  34. Pancake: TPancake;
  35. begin
  36. WriteLn('Working with TStack - pancakes');
  37. WriteLn;
  38. // "Create" a plate of pancakes
  39. PancakesPlate := TStack<TPancake>.Create;
  40. // Bake some pancakes
  41. // Push - puts items on the stack
  42. PancakesPlate.Push(TPancake.Create(ptMeat));
  43. PancakesPlate.Push(TPancake.Create(ptCherry));
  44. PancakesPlate.Push(TPancake.Create(ptCherry));
  45. PancakesPlate.Push(TPancake.Create(ptCurds));
  46. PancakesPlate.Push(TPancake.Create(ptMeat));
  47. // Eating some pancakes
  48. // Pop - removes an item from the stack
  49. Pancake := PancakesPlate.Pop;
  50. Writeln(Format('Ate a pancake (Pop): %s', [Pancake.ToString]));
  51. // Extract - similar to Pop, but causes in OnNotify
  52. // Action = cnExtracted instead of cnRemoved
  53. Pancake := PancakesPlate.Extract;
  54. Writeln(Format('Ate a pancake (Extract): %s', [Pancake.ToString]));
  55. // What is the last pancake?
  56. // Peek - returns the last item, but does not remove it from the stack
  57. Writeln(Format('Last pancake: %s', [PancakesPlate.Peek.ToString]));
  58. // Show the remaining pancakes
  59. Writeln;
  60. Writeln(Format('Total pancakes: %d', [PancakesPlate.Count]));
  61. for Pancake in PancakesPlate do
  62. Writeln(Pancake.ToString);
  63. // Eat up all
  64. // Clear - clears the stack
  65. PancakesPlate.Clear;
  66. FreeAndNil(PancakesPlate);
  67. Readln;
  68. end.