Skip to content

Instantly share code, notes, and snippets.

@lenary
Forked from elliotdavies/test.hs
Last active October 10, 2017 20:40
Show Gist options
  • Select an option

  • Save lenary/bf90bfab852d9b9261dc8b8d7ad4e9c1 to your computer and use it in GitHub Desktop.

Select an option

Save lenary/bf90bfab852d9b9261dc8b8d7ad4e9c1 to your computer and use it in GitHub Desktop.

Revisions

  1. lenary revised this gist Oct 10, 2017. 1 changed file with 10 additions and 1 deletion.
    11 changes: 10 additions & 1 deletion test.hs
    Original file line number Diff line number Diff line change
    @@ -12,6 +12,12 @@ f xs =
    Left s -> Left s
    Right (res3, xs''') ->
    Right (B res1 res2 res3, xs''')

    -- This is exactly `Monad (Either String)`
    f' xs = do (res1, xs') <- f1 xs
    (res2, xs'') <- f2 xs'
    (res3, xs''') <- f3 xs''
    return (B res1 res2 res3, xs''')


    -- In `g` we want to keep trying different functions with the same input
    @@ -26,4 +32,7 @@ g xs =
    Left s ->
    case g3 xs of
    Right (res3, xs') -> Right (res3, xs')
    Left s -> Left s
    Left s -> Left s

    -- this is more complicated, lemme remember what it's called, but it's also possible.
    -- Maybe this is `Alternate (Either String)` but I cannot remember the name immediately.
  2. @elliotdavies elliotdavies created this gist Oct 10, 2017.
    29 changes: 29 additions & 0 deletions test.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    -- In `f` we want to keep piping (part of) the result of one function into
    -- another, and stop as soon as something fails
    f :: [A] -> Either String (B, [A])
    f xs =
    case f1 xs of
    Left s -> Left s
    Right (res1, xs') ->
    case f2 xs' of
    Left s -> Left s
    Right (res2, xs'') ->
    case f3 xs'' of
    Left s -> Left s
    Right (res3, xs''') ->
    Right (B res1 res2 res3, xs''')


    -- In `g` we want to keep trying different functions with the same input
    -- until something succeeds, and then stop
    g :: [A] -> Either String (B, [A])
    g xs =
    case g1 xs of
    Right (res1, xs') -> Right (res1, xs')
    Left s ->
    case g2 xs of
    Right (res2, xs') -> Right (res2, xs')
    Left s ->
    case g3 xs of
    Right (res3, xs') -> Right (res3, xs')
    Left s -> Left s