Advertisement
xxar3s

Untitled

Dec 2nd, 2013
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.29 KB | None | 0 0
  1. module Stacks
  2.  
  3. let private stackEmptyError () = failwith "Stack empty"
  4.  
  5. //1.) Klasická OOP implementácia zásobníka
  6.  
  7. type MutableStack(?stack : MutableStack) =
  8.  
  9.     let mutable list =
  10.         match stack with
  11.         | Some stack -> stack.List
  12.         | _ -> []
  13.  
  14.     member internal s.List = list
  15.  
  16.     member s.Push(value) = list <- value :: list
  17.  
  18.     member s.Pop() =
  19.         let h, t =
  20.             match list with
  21.             | h :: t -> h, t
  22.             | _ -> stackEmptyError()
  23.         list <- t
  24.         h
  25.  
  26.     member s.Top() =
  27.         match list with
  28.         | h :: _ -> h
  29.         | _ -> stackEmptyError()
  30.  
  31. // Použitie
  32.  
  33. let stack = new MutableStack()
  34. stack.Push "aaa"
  35. stack.Push "bbb"
  36. stack.Push "ccc"
  37. printfn "hodnota je %s" (stack.Pop()) //Vypíše "ccc"
  38.  
  39. (****************************************************************************************************)
  40.  
  41. //2.) Funkcionálna implementácia zásobníka
  42.  
  43. module Stack =
  44.  
  45.     let push e list = e :: list
  46.  
  47.     let pop = function
  48.     | _ :: t -> t
  49.     | _ -> stackEmptyError()
  50.  
  51.     let top = function
  52.     | h :: _ -> h
  53.     | _ -> stackEmptyError()
  54.  
  55. // Použitie
  56.  
  57. []
  58. |> Stack.push "aaa"
  59. |> Stack.push "bbb"
  60. |> Stack.push "ccc"
  61. |> Stack.pop |> Stack.top
  62. |> printfn "hodnota je %s" //Vypíše "bbb"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement