Logo

Programming-Idioms

  • Ruby
  • Haskell

Idiom #46 Extract beginning of string (prefix)

Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.

import qualified Data.Text as T
t :: T.Text
t = T.take 5 s

This implementation uses the Text type, imported as suggested in the Text library documentation.
t :: String
t = take 5 s

The function take has two arguments: the number of characters to take as a prefix, and the string to take the prefix from. The function take is in the Haskell prelude and doesn't need to be imported.

The type signature is optional, and could be omitted leaving the second line.
t = s.slice(0...5)
t = s[0, 5]
t = s.slice(0, 5)
T : String := S (1 .. 5);

New implementation...