I’ve been enjoying learning ocaml, but I found it very easy to write code riddled with side effects and imperative-ness.

Take this example:

let some_func arg = 
  let input = format_input_from_stdin ()
  let read_content = read_file "some/file/path.txt"
  let to_write = get_write_file_content input read_content
  let () = write_file "some/other/path.txt" to_write 
  let output = run_external_command_with_output 
  (output, read_content)

As you can see, many side effects and imperative steps in the code. Is there a better practice for coding this in a functional manner?

    • xmunk@sh.itjust.works
      link
      fedilink
      arrow-up
      0
      ·
      10 months ago

      Yea, in nearly every program we still need some amount of I/O which will violate a purely functional approach - we just try to isolate it as much as possible.

      • matcha_addict@lemy.lolOP
        link
        fedilink
        arrow-up
        0
        ·
        10 months ago

        The Haskell approach is to use monads too, right? I can’t seem to understand the benefit of the monad approach

        • oessessnex@programming.dev
          link
          fedilink
          arrow-up
          1
          ·
          edit-2
          10 months ago

          The way you can think of it is that in OCaml everything is implicitly wrapped in an IO monad. In Haskell the IO monad is explicit, so if a function returns something in IO you know it can perform input and output, in OCaml there is no way to tell just from the types. That means that in Haskell the code naturally stratifies into a part that does input and output and a pure core. In OCaml you can do the same thing, however it needs to be a conscious design decision.