4
\$\begingroup\$

I'm trying to transition from JavaScript to PureScript (a Haskell spinoff that transpiles to JavaScript). For starters I coded this:

getAt :: [String] -> Number -> Number -> String
getAt strings x y = case strings !! y of
    Nothing -> " "
    Just line -> case charAt x line of
        Nothing -> " "
        Just char -> fromChar char

-- getAt ["abc", "def"] 0 1 -- returns "d"

It retrieves a character at position (x, y) from a "grid" of characters given as an arrays of strings. I can't help but think that the same function would be just return strings[y][x] in JavaScript assuming that (x, y) are always within bounds - which is true in my case. I can't get rid of these functions that return Maybe, but can I at least write this in a more concise way?

| improve this question | | | | |
\$\endgroup\$
5
\$\begingroup\$

I haven't used PureScript, but in Haskell the most straightforward way to do this would be to leverage the Monad instance for Maybe and write your function using do-notation. From toying around with http://try.purescript.org/ I think this should work.

getAt :: [String] -> Number -> Number -> String
getAt strings x y = fromMaybe " " $ do line <- strings !! y
                                       char <- charAt x line
                                       return $ fromChar char

Note the use of fromMaybe, after you've done your computation in the Maybe monad, you get back out by specifying a "default" to use in the case that any value of Nothing cropped up, causing the whole do-block to return Nothing.

| 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.