prosyslab-classroom / cs348-information-security

61 stars 10 forks source link

[Question][Hw0-2] How to call multiple functions from each other? #199

Closed m-spitfire closed 1 year ago

m-spitfire commented 1 year ago

Name: Murad Bashirov

Hello! When I was doing homework 0-2, I faced a problem with ocaml language. Because the language symbols are defined and available from top to bottom, the function on the top cannot call function on the bottom. And this I needed this while doing calculator problem. I found that when I deal with 2 functions I can use and keyword such (I use : showing that this function calls listed functions in their body:

rec f1: f1, f2
f2: f1
let rec x1 l = l |> abs |> x2

and x2 l = if l < 0 then x1 l else l

But I have a bit more complicated situation:

rec f1: f1, f3
rec f2: f2, f3
f3: f1, f2

In this case I cannot arrange functions and use and keyword to call f3 from both functions and call f1 and f2 from f3. I am not sure what to do.

An example for second case(I know this looks silly):

let rec f1 x =
    if x == 0 then x
    else if x > 0 then f1 (x-1)
    else f3 x

let rec f2 x =
    if x < 0 then f2 (x+1)
    else if x == 0 then 0
    else f3 x

and f3 x =
    if x > 0 then f1 x
    else if x < 0 then f2 x
    else x

ocamlc x.ml gives

File "x.ml", line 3, characters 9-11:
3 |     else f3 x
             ^^
Error: Unbound value f3
KAIST-JongchanPark commented 1 year ago

The and keyword also supports the recursive function.

Therefore,

let rec f1 x =
    if x == 0 then x
    else if x > 0 then f1 (x-1)
    else f3 x

and f2 x =
    if x < 0 then f2 (x+1)
    else if x == 0 then 0
    else f3 x

and f3 x =
    if x > 0 then f1 x
    else if x < 0 then f2 x
    else x

will work well.

m-spitfire commented 1 year ago

Oh thanks for the quick reply!! I was adding rec after and and getting error... Seems interesting that Ocaml requires rec after let-style functions, and not when used with and. Do you think this kind of style is okay? Is using more than one and common?

KihongHeo commented 1 year ago

Hi. Keyword and in let-definition is used to define mutually recursive values and types.