(* calcular fibonacci a partir de várias fontes - ver função calcula *) open Num (* utilizamos a biblioteca Nums para uma aritmética de precisão arbitrária compilação: ocamltop nums.cmxa fib.ml ou ocamlc nums.cma fib.ml *) let mul (a,b,c) (d,e,f) = (a*/d +/ b*/e, a*/e +/ b*/f, b*/e +/ c*/f) let rec pow a n = if n=0 then (Int 1, Int 0, Int 1) (*ID matrix*) else if n=1 then a else let b = pow a (n/2) in if (n mod 2) = 0 then mul b b else mul a (mul b b) let fib n = let (x,_,_) = if n<0 then failwith "Input Negativo" else (pow (Int 1, Int 1, Int 0) n) in x let calcula () = (* recuperar o argv e o seu comprimento (argv é um array de strings)*) let narg = Array.length Sys.argv in (* se o # de argumentos é 1, então ler do stdin*) if narg = 1 then begin print_string "Queira introduzir um valor inteiro: "; let x = read_int() in fib x end else (* se for 2 então o segundo argumento tem de ser um inteiro (lança uma excepção de tipo " invalid cast" caso negativo)*) if narg = 2 then begin fib (int_of_string Sys.argv.(1)) end else if narg>3 then failwith "Bad Use\n" else (* se for igual a 3 e que o segundo é -f então o terceito é o nome do ficheiro por abrir*) if ((Sys.argv.(1) = "-f") && (Sys.file_exists (Sys.argv.(2)))) then begin let fich= open_in Sys.argv.(2) in fib (int_of_string (input_line fich)) end else failwith "Bad Use\n" ;; Printf.printf "resultado = %s\n" (string_of_num (calcula () ))
This document was generated using caml2html