Skip to content

Instantly share code, notes, and snippets.

@scturtle
Created March 10, 2015 09:24
Show Gist options
  • Save scturtle/e6ffa0a83b3e0d1e72f0 to your computer and use it in GitHub Desktop.
Save scturtle/e6ffa0a83b3e0d1e72f0 to your computer and use it in GitHub Desktop.
horspool algorithm
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Map as M (findWithDefault, fromList)
import qualified Data.ByteString as BS
horspool :: BS.ByteString -> BS.ByteString -> Maybe Int
horspool s p = f (lenp - 1) (lenp - 1) (lenp - 1)
where lenp = BS.length p
lens = BS.length s
jmptbl = M.fromList $ zip (BS.unpack p) [lenp - 1, lenp - 2 .. 1]
jmp c = M.findWithDefault lenp c jmptbl
f i j k
| i >= lens = Nothing
| j == -1 = Just (i + 1)
| s `BS.index` i == p `BS.index` j = f (i-1) (j-1) k
| otherwise = let k' = k + jmp (s `BS.index` k)
in f k' (lenp - 1) k'
main :: IO ()
main = do
print $ horspool "aaaabba" "bba"
print $ horspool "ababbbb" "bbbb"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment