Monadic Io with ramanda and ramda fantasy

Trying to figure out how the IO monad works.

Using the code below, I read filenames.txtand used the results to rename files in a directory testfiles. This is clearly incomplete, so instead of actually renaming everything I write, I’m console. :)

My questions:

  • I call twice runIO, but it seems to me that it needs to be called once, in the end?
  • I want to use renameIOinstead renaneDirect, but cannot find the correct syntax.

Any other suggestions are also welcome, I'm new to FP!

    var R = require('ramda');
    var IO = require('ramda-fantasy').IO
    var fs = require('fs');

    const safeReadDirSync = dir => IO(() => fs.readdirSync(dir));
    const safeReadFileSync = file => IO(() => fs.readFileSync(file, 'utf-8'));

    const renameIO = (file, name) => IO(() => console.log('Renaming file ' + file + ' to ' + name + '\n'));
    const renameDirect = (file, name) => console.log('Renaming file ' + file + ' to ' + name + '\n');

    safeReadFileSync("filenames.txt") // read future file names from text file
            .map(R.split('\n')) // split into array
            .map(R.zip(safeReadDirSync('./testfiles/').runIO())) // zip with current file names from dir
            .map(R.map(R.apply(renameDirect))) // rename
            .runIO(); // go!
+4
source share
1 answer

.

runIO, , IO Ramda Fantasy Apply fantasyland spec. (, renameDirect), IO , IO.

R.ap, ( IO) IO (a -> b) -> IO a -> IO -> b. , IO, , a b, IO, a, IO, b.

, R.zip, R.apply(renameDirect), , R.zipWith(renameDirect).

:

var R = require('ramda')
var IO = require('ramda-fantasy').IO
var fs = require('fs')

const safeReadDirSync = dir => IO(() => fs.readdirSync(dir));
const safeReadFileSync = file => IO(() => fs.readFileSync(file, 'utf-8'))
const renameDirect = (file, name) => console.log('Renaming file ' + file + ' to ' + name + '\n')

const filesIO = R.map(R.split('\n'), safeReadFileSync('filenames.txt'))
const testfilesDirIO = safeReadDirSync('./testfiles/')

const renameDirectIO = (files, names) =>
  R.ap(R.map(R.zipWith(renameDirect), files), names)

renameDirectIO(testfilesDirIO, filesIO).runIO()

IO (a -> b) , R.map(R.zipWith(renameDirect), files), R.zipWith(renameDirect) , files. R.ap names, IO, - IO(() => R.zipWith(renameDirect, value.runIO(), names.runIO())

, R.map R.ap , R.lift > , , , Apply.

, :

const renameDirectIO = (files, names) =>
  R.ap(R.map(R.zipWith(renameDirect), files), names)

:

const renameDirectIO = R.lift(R.zipWith(renameDirect))
+9

Source: https://habr.com/ru/post/1656878/


All Articles