Tuesday, April 6, 2021

April 2021 1HaskellADay 1Liners Problems and Solutions

  • 2021-04-20, Tuesday:

    So, I had this problem

    I have pairs :: [(a, IO [b])]

    but I want pairs' :: IO [(a, b)]

    sequence a gives me something like I don't know what: distributing the list monad, not the IO monad. Implement:

    sequence' :: [(a, IO [b])] -> IO [(a, b)]

    • p h z @phaazon_:
      fmap join . traverse (\(a, io) -> fmap (map (a,)) io)
    • lucas卞dicioccio, PhD @lucasdicioccio:

      Just to annoy you I'll use the list-comprehension syntax you dislike.

      solution xs = sequence [fmap (a,) io | (a, io) <- xs]

    • Benkio @benkio89:
      fmap concat . traverse (\(a,iobs) -> fmap (a,) <$> iobs)
    • Social Justice Cleric @noaheasterly
      fmap concat . traverse (getCompose . traverse Compse)
    • Social Justice Cleric @noaheasterly
      fmap (concatMap getCompose) . getCompose . traverse Compose. Compose
    • Basile Henry @basile_henry: Slightly less polymorphic:
      sequence' = traverse @[] (sequence @((,) _) @IO)
    • Basile Henry @basile_henry: I think it's just
      traverse sequence ;)
    • Jérôme Avoustin @JeromeAvoustin: there surely is a shorter version, but I could come up with...
      fmap join . sequence . (fmap . fmap) sequence . fmap sequence
  • 2021-04-16, Friday:

    You have a monad, or applicative, and you wish to execute the action of the latter but return the result of the former. The simplest representation for me is:

    pass :: IO a -> b -> IO b

    so:

    return 5 >>= pass (putStrLn "Hi, there!")

    would return IO 5

    GO!

    • D Oisín Kidney @oisdk flip (<$)
    • ⓘ_jack @Iceland_jack ($>)
  • 2021-04-12, Monday:

    A function that takes the result of another function then uses that result and the original pair of arguments to compute the result:

    f :: a -> a -> b
    g :: b -> a -> a -> c

    so:

    (\x y -> g (f x y) x y)

    curry away the x and y arguments.

  • 2021-04-07, Wednesday:
    you have (Maybe a, Maybe b)
    you want Maybe (a, b)

    If either (Maybe a) or (Maybe b) is Nothing
    then the answer is Nothing.

    If both (Maybe a) and (Maybe b) are (Just ...)
    then the answer is Just (a, b)

    WHAT SAY YOU?

    • Jérôme Avoustin @JeromeAvoustin: bisequence
    • p h z @phaazon_ with base: uncurry $ liftA2 (,)
    • greg nwosu @buddhistfist: (,) <$> ma <*> mb

Thursday, April 1, 2021

April 2021 1HaskellADay Problems and Solutions