Programming Praxis – Brute Force

Today’s Programming Praxis post is another easy one. We have to implement a brute-force string search. Let’s get started.

Our import:

import Data.List

Since it’s no extra effort, we’ll just make our search function generic.

bruteSearch :: Eq a => [a] -> Maybe Int -> [a] -> Maybe Int
bruteSearch n o = fmap fst . find (isPrefixOf n . snd) .
                  drop (maybe 0 id o) . zip [0..] . tails

With that out of the way, let’s define our test suite:

test :: (String -> Maybe Int -> String -> Maybe Int) -> IO ()
test f = do print $ f ""   Nothing  "Hello World" == Just 0
            print $ f "He" Nothing  "Hello World" == Just 0
            print $ f "od" Nothing  "Bonsai Code" == Just 8
            print $ f "ef" Nothing  "Bonsai Code" == Nothing
            print $ f ""   (Just 1) "Hello World" == Just 1
            print $ f "He" (Just 1) "Hello World" == Nothing
            print $ f "od" (Just 1) "Bonsai Code" == Just 8
            print $ f "ef" (Just 1) "Bonsai Code" == Nothing

And let’s run it to see if everything’s in order.

main :: IO ()
main = test bruteSearch

It works fine, but obviously it’s not the most efficient search algorithm. For that you’ll have to wait for the upcoming other search algorithms.

About these ads

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: