Matthias Braun
Matthias Braun

Reputation: 34373

Check if string starts with other string in Haskell

I'd like to know whether my string starts with another string. For example:

startsWith "(" "(test string)" == True

Is there such a function that comes with Haskell?

Upvotes: 10

Views: 9062

Answers (2)

chi
chi

Reputation: 116174

Since strings are lists of characters, we can import Data.List and use the general function isPrefixOf:

isPrefixOf :: Eq a => [a] -> [a] -> Bool

Example:

Prelude Data.List> isPrefixOf "abc" "abcxyz"
True

Upvotes: 18

Matthias Braun
Matthias Braun

Reputation: 34373

with Data.Text

You can use isPrefixOf to check whether one string starts with another:

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T

T.isPrefixOf "(" "(test string)"

To include Data.Text in your project, add text as a dependency in your Cabal file:

build-depends:
    base >=4.7 && <5
  , text

Upvotes: 5

Related Questions