Coordinate in List

Viewed 45

I am trying to figure out how to search for a character in a string of character that will output its coordinate.

I am trying to search for the character 'A'

The list is:

["OPQ","EAB","XGV"]

The function is:

searchA :: [[Char]] -> (Int,Int)

The user then calls the function as such:

searchA ["OPQ","EAB","XGV"]

I am expecting an output of (1,1)

Sorry guys, new to stackoverflow and haskell

1 Answers

Code which solve your task:

import Data.List (find)
import Data.Maybe (fromJust)

-- ...

searchA :: [[Char]] -> Maybe (Int,Int)
searchA css = do
    (n, cs) <- find (elem 'A' . snd) (zip [0..] css)
    (m, _)  <- find ((== 'A') . snd) (zip [0..] cs)
    return (n,m)

Here output type is Maybe (Int,Int) because you can not found letter 'A'.

If you actually want type (Int,Int), you can use fromJust function, but your code will be unsafe:

searchA' :: [[Char]] -> (Int,Int)
searchA' css =
    let (n, cs) = fromJust $ find (elem 'A' . snd) (zip [0..] css)
        (m, _)  = fromJust $ find ((== 'A') . snd) (zip [0..] cs)
    in  (n,m)

You can also use function ifind from package lens:

import Control.Lens (ifind)

searchA'' :: [[Char]] -> (Int,Int)
searchA'' css =
    let (n, cs) = fromJust $ ifind (\_ -> elem 'A') css
        (m, _)  = fromJust $ ifind (\_ -> (== 'A')) cs
    in  (n,m)
Related