Commits

arkdro  committed ea7905e

add divide api

  • Participants
  • Parent commits 07d4254

Comments (0)

Files changed (2)

File erlang/src/c_server.erl

 -behaviour(gen_server).
 
 -export([
+         divide/2,
          subtract/2,
          sum/1,
          info/1,
 subtract(N1, N2) ->
     gen_server:call(?SERVER, {subtract, N1, N2}).
 
+divide(N1, N2) ->
+    gen_server:call(?SERVER, {divide, N1, N2}).
+
 %-------------------------------------------------------------------
 start_link() ->
     gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
     Cmd = term_to_binary({subtract, N1, N2}),
     port_command(Port, Cmd),
     {noreply, State#state{from=From}};
+handle_call({divide, N1, N2}, From,
+            #state{status=running, port=Port} = State) ->
+    Cmd = term_to_binary({divide, N1, N2}),
+    port_command(Port, Cmd),
+    {noreply, State#state{from=From}};
 handle_call(stop, _From, St) ->
     {stop, normal, ok, St};
 handle_call(status, _From, St) ->

File ocaml/src/odec_port.ml

   | _ ->
     ET_Tuple [ET_Atom "error"; ET_Atom "not_decimal"]
 
+let divide d1 d2 =
+  let t1 = make_tuple d1 in
+  let t2 = make_tuple d2 in
+  match t1, t2 with
+  | Some _, Some _ ->
+    let (Some n1) = make_num t1 in
+    let (Some n2) = make_num t2 in
+    let res = Num.div_num n1 n2 in
+    let dec_res = create_decimal res in
+    ET_Tuple [ET_Atom "ok"; dec_res]
+  | _ ->
+    ET_Tuple [ET_Atom "error"; ET_Atom "not_decimal"]
+
 let port_command_dispatcher old_value = function
   | ET_Tuple [ET_Atom "forget"; _] ->
     None, ET_Atom "ok"
   | (ET_Tuple [ET_Atom "subtract"; t1; t2]) as t ->
     let res = subtract t1 t2 in
     Some t, res
+  | (ET_Tuple [ET_Atom "divide"; t1; t2]) as t ->
+    let res = divide t1 t2 in
+    Some t, res
   | _ -> raise (Failure "Unknown command")
   ;;