1
\$\begingroup\$

The following function appends a tuple to two Maybe [a]'s.

tupleToMaybeList :: (a, a) -> Maybe [a] -> Maybe [a] -> Maybe [a]
tupleToMaybeList (a, b) cs ds = do
    x  <- return a
    y  <- return b
    xs <- cs
    ys <- ds
    return ((x : y : xs) ++ ys)

Please critique it for idiomatic Haskell-ness.

\$\endgroup\$
  • 3
    \$\begingroup\$ Can you explain what problem you are trying to solve? \$\endgroup\$ – Gareth Rees May 5 '15 at 16:00
5
\$\begingroup\$

There's a bit of redundancy in your implementation. b <- return a is effectively the same as let b = a. There's no need to “inject” pure values into a monadic context with return, a pure value in scope is a pure value in scope so just use a and b in place of your x and y.

The parentheses around x : y : xs are also technically redundant. Regardless of the ordering of the application of x : y : and xs ++ ys you'll still end up with the same list. This is always the case for list cons and append, if you think about it you should see why. Note that the fixity precedence for both functions is infixr 5.

prependTupleConcatMaybeLists :: (a, a) -> Maybe [a] -> Maybe [a] -> Maybe [a]
prependTupleConcatMaybeLists (a, b) cs ds =
  do xs <- cs
     ys <- ds
     return $ a : b : xs ++ ys

I do question the necessity of writing this particular function. Concatenating cs and ds should probably be taken care of separately to prepending a tuple to a list. E.g.,

prependTupleMaybe :: (a, a) -> Maybe [a] -> Maybe [a]
prependTupleMaybe (a, b) xs = fmap (a:b:) xs

-- call site: let zs = liftA2 (++) (prependTupleMaybe pair xs) ys
-- or       : let zs = prependTupleMaybe pair (liftA2 (++) xs ys)
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.