Skip to content

Instantly share code, notes, and snippets.

@aratama
Last active July 15, 2018 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aratama/ee3ec6caa42ce3c5c984e4e6e333aeed to your computer and use it in GitHub Desktop.
Save aratama/ee3ec6caa42ce3c5c984e4e6e333aeed to your computer and use it in GitHub Desktop.
RowToList Excercise: Promise.props
exports.objectToArray = function(xs){
return Object.keys(xs).sort().map(function(key){
debugger
return xs[key]
})
}
exports.arrayToObject = function(xs){
return function(values){
const row = {}
Object.keys(xs).sort().forEach(function(key, i){ row[key] = values[i] })
return row
}
}
module Main where
import Control.Parallel (parSequence)
import Control.Parallel.Class (sequential, parallel)
import Effect (Effect)
import Effect.Aff (Aff, launchAff_)
import Effect.Class.Console (logShow)
import Node.Encoding (Encoding(..))
import Node.FS.Aff (readTextFile, readdir)
import Prelude (Unit, bind, discard, pure, ($), (<$>), (<*>))
import Prim.RowList (class RowToList, Cons, Nil, kind RowList)
import Type.Row (class ListToRow)
class Extract (xs :: RowList) (ys :: RowList) | xs -> ys
instance extractNil :: Extract Nil Nil
else instance extractCons :: Extract ys zs => Extract (Cons key (Aff value) ys) (Cons key value zs)
foreign import objectToArray :: forall row heterogenous.
Record row -> Array (Aff heterogenous)
foreign import arrayToObject :: forall row row' heterogenous.
Record row -> Array heterogenous -> Record row'
props :: forall row row' list list'.
RowToList row list
=> Extract list list'
=> ListToRow list' row'
=> Record row -> Aff (Record row')
props tasks = arrayToObject tasks <$> parSequence (objectToArray tasks)
main :: Effect Unit
main = launchAff_ do
-- applicative style
results' <- sequential $ { foo: _, bar: _, dir: _, baz: _ }
<$> parallel (readTextFile UTF8 "foo.txt")
<*> parallel (readdir ".")
<*> parallel (pure 42 :: Aff Int)
<*> parallel (readTextFile UTF8 "baz.txt")
logShow results'
-- props style
results <- props {
foo: readTextFile UTF8 "foo.txt",
dir: readdir ".",
bar: pure 42 :: Aff Int,
baz: readTextFile UTF8 "baz.txt"
}
logShow results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment