HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Maybe getting a character from a list of strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
charactergettingmaybelistfromstrings

Problem

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?

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#84773, answer score: 6

Revisions (0)

No revisions yet.