0
votes

The function 'succ_di_nodo' prints the successors of a given node in a given graph:

type peso = int;;
type 'a grafo = Gr of (int * peso * int) list;;
let g1 =  Gr [(1,3,2);(1,9,5);(2,2,3);(5,4,6);(3,1,6);(3,7,4);(6,2,7);(4,4,6)];;

let rec succ_di_nodo (Gr grafo) nodo =
    let rec f_ausiliaria = function
        [] -> []
        | (x,y,z)::coda -> 
            if x = nodo then z::f_ausiliaria coda
            else if z = nodo then x::f_ausiliaria coda
            else f_ausiliaria coda in f_ausiliaria grafo;;

g1 is the Graph itself and the value are (node1,weight,node2). When i pass to the function succ_di_nodo the value for example (succ_di_nodo g1 4) it returns correctly: int list = [3;6].

The question is, when i call the function (succ_di_nodo g1) without giving a specific node it return the type int -> int list; so it is not an empty list and i want to see the exact return value of this function call. How can i print the type int -> int list in Ocaml?

1

1 Answers

0
votes

When you call succ_di_nodo with only one argument it returns a function that accepts the second argument and returns the list of successors. This is called partial application.

The int -> int list type denotes a function that takes one argument of type int and returns a value of type int list. You can't print a function value (the default printer will just print <fun>). In order to print a function, you would need to enumerate all values in the input domain, which is usually infinite (or close to that). For testing purposes, you can, of course, apply you function to a set of input values, to see what it outputs, e.g.,

List.init 10 (succ_di_nodo g1);;

will apply (succ_di_nodo g1) to 0, 1, and so on up to 9 and return the result in a list, i.e., the output will be

[[]; [2; 5]; [1; 3]; [2; 6; 4]; [3; 6]; [1; 6]; [5; 3; 7; 4]; [6]; []; []]

You can also trace your function in a toplevel (i.e., when you are running your function in the interpreter), by using the #trace directive. It will show the arguments that go into the function and values that go out. For the sake of experiment try this in the toplevel:

#trace succ_di_nodo;;

(you need to type the leading # it is a part of the directive name). When you will apply succ_di_nodo to two arguments, you will notice that the function first returns a new function, codenamed succ_di_nodo*, which is the result of the application of the first argument, and, finally, the second argument is passed to the returned succ_di_nodo* function. This process is called currying, which is an essential concept in functional programming.

# #trace succ_di_nodo;;
succ_di_nodo is now traced.
# succ_di_nodo g1 0;;
succ_di_nodo <--
  Gr
   [(1, 3, 2); (1, 9, 5); (2, 2, 3); (5, 4, 6); (3, 1, 6); (3, 7, 4);
    (6, 2, 7); (4, 4, 6)]
succ_di_nodo --> <fun>
succ_di_nodo* <-- 0
succ_di_nodo* --> []
- : int list = []
# 

When you are done, you can untrace a function with the #untrace directive.