user3434886
user3434886

Reputation: 5

Haskell Get position from first digit in string

What I got is

digitIndex :: String -> Int
digitIndex [] = 1
digitIndex (x:xs) =
    if
        isDigit x == True
    then
        -- Count list
    else
        -- Create list with x(x is not a digit)

What my idea is is to make a list with all the x that he is passing so when he passes a digit he only needs to count the list and that will be the position of the digit(when you count a +1).

Only thing is I don't know how to get the job more done. Can you guys help me out with tips?

Upvotes: 0

Views: 958

Answers (2)

Sibi
Sibi

Reputation: 48644

Just the normal recursion:

digitIndex :: String -> Int
digitIndex [] = 0
digitIndex (x:xs) = if isDigit x
                    then 1
                    else 1 + digitIndex xs

If the first character itself is a digit, then the function returns 1 else it just adds 1 and passes the remaining string (xs) to the function and the recursion goes on.

Also note that the above function doesn't work properly when the String doesn't have a number at all.

And also checking isDigit == True isn't necessary.

Upvotes: 0

Lee
Lee

Reputation: 144126

You can use findIndex:

import Data.List

digitIndex :: String -> Int
digitIndex = maybe 0 id . findIndex isDigit

Upvotes: 3

Related Questions