Haskell's "built in" string type is called String
, and it's actually just a list of Char
. In fact, if you try entering a list of Char
at the GHCi prompt, it'll print it back to you in its String
syntax:
> ['a','b','c']
"abc"
For "real" code, String
is usually a terrible choice because it has all the performance you'd expect from a linked list of characters. But, it's good enough for experimenting when you're learning Haskell. You can learn about alternatives like Text
later.
Because String
is a list of char, take
and drop
work on it just like they work on a list:
> take 3 [1,2,3,4,5]
[1,2,3]
> take 3 "abcde"
"abc"
They act on the start of the string, so if you want a general substring function, you need to first drop
the beginning part of the string you don't want, and then take
the substring you do want. For example, to get "bc"
out of "abcde"
, you want to drop "a"
:
> drop 1 "abcde"
"bcde"
and then take "bc"
:
> take 2 (drop 1 "abcde")
"bc"
The rest is just math -- the first number "2" should -- in general -- be the length of the desired substring. The second number "1" should -- in general -- be the starting position (offset zero).
So, try filling in the "???" below with expressions involving m
and n
, and if you're still stuck, post an edit or a follow-up question:
substr :: Int -> Int -> String -> String
substr m n str = take ??? (drop ??? str)