I'm trying to implement a subString function which has a conditional part:
"This function can accept negative start and end position. Negative start position can be considered as zero (e.g. substring from the first character) and negative end position should result in an empty string." My current solution looks like this , however something is definitely wrong because ghc not recognizing it with :"Variable not in scope: subString"(the loading part is working maybe indentation error? )
subString :: Int -> Int -> String -> String
subString start end str | (start <= 0) && (end > 0) = take (end 1) str
| (start > 0) && (end <= 0) = []
| otherwise = take ((end 1) - start )(drop start str)
Thanks for the help
CodePudding user response:
I've messed up the reload part and the code was fine, thanks four your reply tho. If anyone interested the correct solution for the exercise was :
subString :: Int -> Int -> String -> String
subString start end str | (start <= 0) && (end >= 0) = take (end 1) str
| (start > 0) && (end <= 0) = []
| (start < 0) && (end < 0) = []
| otherwise = take ((end 1) - start )(drop start str)
CodePudding user response:
There is no need to split this up in separate cases: if drop :: Int -> [a] -> [a]
receives a negative number, it will not drop anything, so you can implement this as:
subString :: Int -> Int -> [a] -> [a]
subString start end
| end < 0 = const []
| otherwise = take (end - max 0 start 1) . drop start