Akshay Hazari
Akshay Hazari

Reputation: 3267

String Matching with newline character in Haskell

Here I am trying to find the index of '-' followed by '}' in a String.

For an input like sustringIndex "abcd -} sad" it gives me an output of 10 which is giving me the entire string length.

Also if I do something like sustringIndex "abcd\n -} sad" it gives me 6

Why is that so with \n. What am I doing wrong. Please correct me I'm a noob.

substrIndex :: String -> Int
substrIndex ""=0
substrIndex (s:"") = 0
substrIndex (s:t:str)
  | s== '-' && t == '}' = 0
  | otherwise = 2+(substrIndex str)

Upvotes: 1

Views: 222

Answers (1)

thefourtheye
thefourtheye

Reputation: 239593

Your program has a bug. You are checking every two characters. But, what if the - and } are in different pairs, for example S-}?

  1. It will first check S and - are equal to - and } respectively.

  2. Since they don't match, it will move on with } alone.

So, you just need to change the logic a little bit, like this

substrIndex (s:t:str)
  | s == '-' && t == '}' = 0
  | otherwise = 1 + (substrIndex (t:str))

Now, if the current pair doesn't match -}, then just skip the first character and proceed with the second character, substrIndex (t:str). So, if S- doesn't match, your program will proceed with -}. Since we dropped only one character we add only 1, instead of 2.


This can be shortened and written clearly, as suggested by user2407038, like this

substrIndex :: String -> Int
substrIndex [] = 0
substrIndex ('-':'}':_) = 0
substrIndex (_:xs) = 1 + substrIndex xs

Upvotes: 4

Related Questions