0

I am using haskell and the following:

convertToBasis :: [String] -> Maybe [Basis] convertToBasis [] = Nothing convertToBasis (h:t) = basis : convertToBasis t where basis = toCandidateBasis h 

Returns a type of [Maybe Basis] I want a type of Maybe [Basis] toCandidateBasis is shown below:

toCandidateBasis :: String -> Maybe Basis toCandidateBasis myStr = if not $ has7UniqueLetters myStr [] then Nothing else Just (dedupAndSort myStr) 

The function returns nothing if a String does not have 7 unique characters otherwise it removes duplicates and sorts the String alphabetically and return that result. Now the return type of the function is Maybe Basis. Hence when I when I get a list of strings and want to convert them to their respective candidate basises one by one, it will concat all the maybes and return me a type of:

[Maybe Basis] 

But I want a type of

Maybe [Basis] 

It should return Nothing only when the given Basis array is empty otherwise return some result. How do I do this?

3
  • 4
    "return Nothing only when the given Basis array is empty" Buy why? If Just [] is impossible, then there's no point in returning a Maybe at all. "non-empty list or nothing" conveys the same values as "possibly-empty list". Commented Sep 30, 2022 at 19:04
  • Because if you have lets say a list of ["IS String", [], "String"] you want to return ["IS String", "String"] not the original thing back. Commented Sep 30, 2022 at 21:59
  • 1
    I don't see any Maybes in that example. And it's easy to turn the former into the latter without messing with Maybe: filter (not . null). Commented Sep 30, 2022 at 22:49

1 Answer 1

3

There's really no reason to use a Maybe [a] unless there is a semantic difference between Nothing and Just [], which it sounds like there is not in your case. However, it is a fairly common use case to reduce a list [Maybe a] to a list [a] by removing all the Nothings— so common, in fact, that there's a builtin function for doing that: catMaybes :: [Maybe a] -> [a].

Sign up to request clarification or add additional context in comments.

6 Comments

toCandidateBasis = traverse convertToBasis is also a definition of a reasonable alternative thing to want here.
@amalloy Do you mean convertToBasis = traverse toCandidateBasis? It doesn't work the other way.
Oh, of course. I copied the wrong names.
But if I tried to use a head operation on Maybe [a] it will complain stating that Couldn't match expected type: [Maybe Basis] with actual type: Maybe [Basis]
@chen that's why everyone is saying you should use [Basis] instead of Maybe [Basis]
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.