Advertisement
Guest User

Untitled

a guest
Nov 19th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.05 KB | None | 0 0
  1. // Learn more about F# at http://fsharp.org
  2.  
  3. open System
  4.  
  5.  
  6. type instruction =
  7.    | ADD (* dodawanie *)
  8.    | SUB (* odejmowanie *)
  9.    | MUL (* mnozenie *)
  10.    | SQR (* podnoszenie do kwadratu *)
  11.    | PUSH of float (* odkladanie na stos *)
  12.    | DIV
  13.  
  14. type Stack = float list
  15. exception WrongProgramException of (instruction * Stack)
  16. exception ErrException of (Stack)
  17. exception ErException
  18.  
  19. let intInstr (x , y) =
  20.    match x , y with
  21.    | ADD, a::b::ys -> (b + a) :: ys : Stack
  22.    | SUB, a::b::ys -> (b - a) :: ys
  23.    | MUL, a::b::ys -> (b * a) :: ys
  24.    | SQR, a::ys -> (a * a) :: ys
  25.    | PUSH x, ys -> x::ys
  26.    | DIV, a::b::ys -> try
  27.                           Some (b / a) :: ys
  28.                       with
  29.                            | :? System.DivideByZeroException -> printfn "Division by zero!";
  30.    | _, _ -> raise ErException;
  31.  
  32. let wypisz_instr = function
  33.     | ( PUSH x) -> "PUSH " + System.Convert.ToString(x)
  34.     | ( SQR ) -> " SQR "
  35.     | ( ADD ) -> " ADD "
  36.     | ( SUB ) -> " SUB "
  37.     | ( MUL ) -> " MUL "
  38.     | ( DIV ) -> " DIV "
  39.  
  40. let rec wypisz is =
  41.     match is with
  42.     | x::is -> printfn "%A" (wypisz_instr x); wypisz(is)
  43.     | _ -> []
  44.  
  45. let intpProg(is) =
  46.     let rec iPS = function
  47.     | ([],x::xs) -> x
  48.     | (i::is, xs) -> try
  49.                          iPS(is, intInstr(i, xs))
  50.                      with
  51.                          ErException -> ( wypisz(is); 0.0 )
  52.     | _ -> 0.0
  53.     iPS(is,[]) (* start programu, stos początkowo pusty *)
  54.  
  55.  
  56. [<EntryPoint>]
  57. let main argv =
  58.     // WPROWADZENIE
  59.     let i1 = PUSH 3.0
  60.     let i2 = PUSH 4.0
  61.     let i3 = ADD
  62.     let stos:Stack = []    (* lista pusta musi być określonego typu *)
  63.     let stos1 =  intInstr(i1,stos)
  64.     let stos2 =  intInstr(i2,stos1)
  65.     let stos3 =  intInstr(i3,stos2)
  66.  
  67.     // printfn "%A" stos3
  68.  
  69.     let il1 = [PUSH 3.0; PUSH 4.0; ADD; PUSH 2.0; MUL; MUL; MUL; MUL]
  70.     let w = intpProg(il1)
  71.     printfn "%A" w
  72.  
  73.  
  74.     let il2 = [PUSH 4.0; PUSH 0.0; DIV]
  75.     let w = intpProg(il2)
  76.     printfn "%A" w
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.     0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement