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?
-
2Please don't vandalize your own posts. If it is necessary to remove them, flag for moderator attention and ask for removal.S.L. Barth is on codidact.com– S.L. Barth is on codidact.com2014年03月19日 15:09:27 +00:00Commented Mar 19, 2014 at 15:09
2 Answers 2
You can use findIndex
:
import Data.List
digitIndex :: String -> Int
digitIndex = maybe 0 id . findIndex isDigit
Comments
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.