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?

  • ornery_chemist@mander.xyz
    link
    fedilink
    arrow-up
    1
    ·
    4 months ago

    True Functional Programmers will probably correct my lack of nuance here, but my understanding is that the IO monad is basically just scribbling some category theory formalities on top of IO ops so that everything is still technically a pure function. You can think of the IO monad as representing the “state” of the rest of the universe outside of your program, which your program reads or modifies. As you pass through your monadic bind ops (i.e., as you read or write IO), the state is carried through implicitly and “modified” as appropriate. All functions, then, are just transforming data (i.e., either your program’s data or the rest of the universe), so everything is pure.