-4

I'm trying to implement the Haskell equivalent of the Python:

> "abcdef"[1:3]
'bcd'

In fact, I'll try using the Haskell language for the first time. I do not know how to handle strings(or text???)

substr :: Text -> Int -> Int -> Text ???? I try to use 'take' and 'drop', but I do not know the exact order and function combination.

substr "abcdef" 1 3
“bcd”
CPUU
  • 71
  • 2
  • 7

1 Answers1

8

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)
K. A. Buhr
  • 45,621
  • 3
  • 45
  • 71
  • Thanks for your information. I think ```take (n-m) (drop m str)``` but, error occurs. Variable not in scope: substr :: [Char] -> Integer -> Integer -> t – CPUU Jul 04 '19 at 15:08
  • My two-line example above was meant to go in a "xxx.hs" file and be loaded. It sounds like you tried to enter it at the GHCi interactive prompt. If so, the first line will give that error. This question might help: https://stackoverflow.com/questions/45362445/defining-function-signature-in-ghci. – K. A. Buhr Jul 04 '19 at 15:12
  • Can I ask one more? How can I check the bounds? for example, if the length of str is 15, then ( n > m ) && ( 0 < m, n < 15 ) will must be true – CPUU Jul 04 '19 at 15:19
  • @CPUU No, you can't. New question is a new post. –  Jul 04 '19 at 17:37