Guest User

Untitled

a guest
Jan 26th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.26 KB | None | 0 0
  1. %List2
  2. %2
  3. declare fun {Fib1 N}
  4.        if N==0 then 0 elseif N==1 then 1 else {Fib1 N-1}+{Fib1 N-2} end end
  5.  
  6. {Show {Fib1 37}}
  7. %approx 10 secs
  8.  
  9. declare fun {Fib2 N}
  10.        local fun {TailFib N Acc Next}
  11.             if N == 0 then Acc else {TailFib N-1 Next Acc+Next}
  12.             end
  13.          end
  14.        in {TailFib N 0 1}
  15.        end
  16.     end
  17.        
  18. {Show {Fib2 37}}
  19. %Less than 1 sec
  20.  
  21. %3.
  22. declare
  23. fun {Root3 A#Eps}
  24.    local
  25.       fun {Licz Acc}
  26.      if {Abs {Pow Acc 3.} - A} =< Eps * {Abs A} then Acc
  27.      else {Licz Acc + (A/{Pow Acc 2.} - Acc)/3.}
  28.      end
  29.       end
  30.    in if A>=1. then {Licz A/3.} else {Licz A} end
  31.    end
  32. end
  33.  
  34. {Show {Root3 64.0#0.001}}
  35.  
  36. %4.
  37. declare X = 0
  38. %a)
  39. declare _|_|X|_|_|nil = ~2|~1|0|1|2|nil
  40. %b)
  41. declare _#_|X#_|nil = 1#2|0#1|nil
  42.  
  43. %5.
  44. declare fun {Initsegment L1#L2}
  45.        case L1 of
  46.           nil then true
  47.        [] H|T then if L2 == nil then false
  48.                elseif H == L2.1 then {Initsegment T#L2.2} else false
  49.                end
  50.        end
  51.     end
  52. %6.
  53. declare fun {Replace_nth L#N#V}
  54.        if {Length L} < N then raise 'List length is less than n'
  55.                   end
  56.        else case L of
  57.            nil then raise 'List is empty'
  58.                 end
  59.         [] H|T then if N==0 then V|T else H|{Replace_nth T#N-1#V}
  60.                 end
  61.         end
  62.        end
  63.     end
  64.  
  65. {Show {Replace_nth (1|2|3|4|5|nil)#3#0}}
Add Comment
Please, Sign In to add comment