# Amazing result hand made search with F#

**URL:** <https://forums.fsharp.org/t/amazing-result-hand-made-search-with-f/4110>\
**Category:** General\
**Tags:** beginners\
**Created:** [January 4, 2025, 4:20am UTC](https://forums.fsharp.org/t/amazing-result-hand-made-search-with-f/4110 "2025-01-04T04:20:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![altbodhi](https://yyz2.discourse-cdn.com/flex030/user_avatar/forums.fsharp.org/altbodhi/32/1253_2.png) [@altbodhi](https://forums.fsharp.org/u/altbodhi)\
**Post date:** [January 4, 2025, 4:20am UTC](https://forums.fsharp.org/t/amazing-result-hand-made-search-with-f/4110/1 "2025-01-04T04:20:23Z")

</div>

I am reading Algoritms Nikolas Wirt and re-write find substring by example from book

```auto
    module Text =

        /// поиск индекс первого вхождения образца в строке
        let findFirst (s: string) (p: string) =
            // предикат проверяющий совпадение части строки с образцом
            let eqSample i (s: string) (p: string) =
                let rec loop j =
                    if j < p.Length && p.[j] = s.[i + j] then
                        loop (j + 1)
                    else
                        j
                loop 0

            let rec loop i =
                if i <= s.Length - p.Length then
                    let dx = eqSample i s p
                    if dx = p.Length then i // нашли подстроку
                    else loop (i + dx + 1)
                else -1 // Возвращаем -1, если не найдено
            
            if p.Length > s.Length || p.Length = 0 
            then -1
            else loop 0

```

```auto
> content.IndexOf substring;;
Real: 00:00:00.023, CPU: 00:00:00.023, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 468658

> Text.findFirst content substring;;
Real: 00:00:00.003, CPU: 00:00:00.003, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 468658

```

It is fine!

---

<div class="post-metadata">

**Author:** ![frank58richard](https://avatars.discourse-cdn.com/v4/letter/f/aeb1de/32.png) [@frank58richard](https://forums.fsharp.org/u/frank58richard)\
**Post date:** [February 7, 2025, 4:40am UTC](https://forums.fsharp.org/t/amazing-result-hand-made-search-with-f/4110/3 "2025-02-07T04:40:49Z")

</div>

Hello,  
you’ve successfully implemented and tested the findFirst function for finding the first occurrence of a substring in a string using a custom algorithm. The implementation is working as expected and performs quite efficiently, as you’ve observed that the execution time for your version is faster than using content.IndexOf.

The core logic you’ve used to search for the substring seems to break down the problem well, with the helper function eqSample checking for character-by-character equality [readworks.oge](https://www.read-theory.com) and your loop function iterating through the string to find a match.

Best Regard,  
Frank
