FSM substring search on scheme












0














I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The Idea was to use this routines as a mean to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.



This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.



NOTES:




  1. I know that using lists might not be the most efficient thing to do but they allowed me to program in a more functional way without using vector-set!


  2. If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.


  3. Sadly emacs uses tabs for indentation so formatting may be a little messy.



An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to.
If no pair contains a specific character then it defaults to the invalid state (index = 0).



the run-automata function searches a matching substring and returns its offset or #f is it is not contained inside string.



Thanks for you time!



(define (string-null? s) (= (string-length s) 0))
(define (string-append-c s c) (string-append s (string c)))
(define (string-tail str) (substring str 1 (string-length str)))

;; is s2 a prefix of s1?
;; [TODO] - Use offset instead of string-tail
(define (string-prefix? s1 s2)
(cond ((string-null? s2) #t)
((string-null? s1) #f)
((not (char=? (string-ref s2 0)
(string-ref s1 0))) #f)
(else (string-prefix? (string-tail s1)
(string-tail s2))))
)

(define (enumerate start end)
(define (iter start end acc)
(if (> start end)
acc
(iter start (- end 1) (cons end acc))
)
)

(iter start end '())
)

(define (build-automata needle)
(define (max-suffix-that-is-prefix str)
(cond ((string-null? str) "")
((not (string-prefix? needle str))
(max-suffix-that-is-prefix (string-tail str)))
(else str))
)

(define (build-transitions state-string transitions dictionary)
(if (null? dictionary)
transitions
(let* ((c (car dictionary))
(suffix (max-suffix-that-is-prefix
(string-append-c state-string c))))
(build-transitions
state-string
(if (string-null? suffix)
transitions
(cons (cons c (string-length suffix)) transitions))
(cdr dictionary))
)
)
)

;; Last state does not require a transition as it is the final state.
;; "We are done by that point".
(let ((dictionary (string->list "abcdefghijkmnopqrstuvwxyz")))
(map (lambda (n)
(build-transitions (substring needle 0 n) '()
dictionary))
(enumerate 0 (- (string-length needle) 1))
)
)
)

;; Takes an automata and a string and returns the offset of the pattern the
;; automata was built to search
(define (run-automata automata string)
(define (search-transition c state-transitions)
(cond ((null? state-transitions) 0)
((char=? (caar state-transitions) c) (cdar state-transitions))
(else (search-transition c (cdr state-transitions))))
)

(define (step state automata-size offset)
(cond ((= state automata-size)
(- offset automata-size))
((>= offset (string-length string)) #f)
(else
(step (search-transition (string-ref string offset)
(list-ref automata state))
automata-size
(+ offset 1))))
)

(step 0 (length automata) 0)
)








share



























    0














    I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The Idea was to use this routines as a mean to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.



    This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.



    NOTES:




    1. I know that using lists might not be the most efficient thing to do but they allowed me to program in a more functional way without using vector-set!


    2. If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.


    3. Sadly emacs uses tabs for indentation so formatting may be a little messy.



    An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to.
    If no pair contains a specific character then it defaults to the invalid state (index = 0).



    the run-automata function searches a matching substring and returns its offset or #f is it is not contained inside string.



    Thanks for you time!



    (define (string-null? s) (= (string-length s) 0))
    (define (string-append-c s c) (string-append s (string c)))
    (define (string-tail str) (substring str 1 (string-length str)))

    ;; is s2 a prefix of s1?
    ;; [TODO] - Use offset instead of string-tail
    (define (string-prefix? s1 s2)
    (cond ((string-null? s2) #t)
    ((string-null? s1) #f)
    ((not (char=? (string-ref s2 0)
    (string-ref s1 0))) #f)
    (else (string-prefix? (string-tail s1)
    (string-tail s2))))
    )

    (define (enumerate start end)
    (define (iter start end acc)
    (if (> start end)
    acc
    (iter start (- end 1) (cons end acc))
    )
    )

    (iter start end '())
    )

    (define (build-automata needle)
    (define (max-suffix-that-is-prefix str)
    (cond ((string-null? str) "")
    ((not (string-prefix? needle str))
    (max-suffix-that-is-prefix (string-tail str)))
    (else str))
    )

    (define (build-transitions state-string transitions dictionary)
    (if (null? dictionary)
    transitions
    (let* ((c (car dictionary))
    (suffix (max-suffix-that-is-prefix
    (string-append-c state-string c))))
    (build-transitions
    state-string
    (if (string-null? suffix)
    transitions
    (cons (cons c (string-length suffix)) transitions))
    (cdr dictionary))
    )
    )
    )

    ;; Last state does not require a transition as it is the final state.
    ;; "We are done by that point".
    (let ((dictionary (string->list "abcdefghijkmnopqrstuvwxyz")))
    (map (lambda (n)
    (build-transitions (substring needle 0 n) '()
    dictionary))
    (enumerate 0 (- (string-length needle) 1))
    )
    )
    )

    ;; Takes an automata and a string and returns the offset of the pattern the
    ;; automata was built to search
    (define (run-automata automata string)
    (define (search-transition c state-transitions)
    (cond ((null? state-transitions) 0)
    ((char=? (caar state-transitions) c) (cdar state-transitions))
    (else (search-transition c (cdr state-transitions))))
    )

    (define (step state automata-size offset)
    (cond ((= state automata-size)
    (- offset automata-size))
    ((>= offset (string-length string)) #f)
    (else
    (step (search-transition (string-ref string offset)
    (list-ref automata state))
    automata-size
    (+ offset 1))))
    )

    (step 0 (length automata) 0)
    )








    share

























      0












      0








      0







      I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The Idea was to use this routines as a mean to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.



      This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.



      NOTES:




      1. I know that using lists might not be the most efficient thing to do but they allowed me to program in a more functional way without using vector-set!


      2. If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.


      3. Sadly emacs uses tabs for indentation so formatting may be a little messy.



      An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to.
      If no pair contains a specific character then it defaults to the invalid state (index = 0).



      the run-automata function searches a matching substring and returns its offset or #f is it is not contained inside string.



      Thanks for you time!



      (define (string-null? s) (= (string-length s) 0))
      (define (string-append-c s c) (string-append s (string c)))
      (define (string-tail str) (substring str 1 (string-length str)))

      ;; is s2 a prefix of s1?
      ;; [TODO] - Use offset instead of string-tail
      (define (string-prefix? s1 s2)
      (cond ((string-null? s2) #t)
      ((string-null? s1) #f)
      ((not (char=? (string-ref s2 0)
      (string-ref s1 0))) #f)
      (else (string-prefix? (string-tail s1)
      (string-tail s2))))
      )

      (define (enumerate start end)
      (define (iter start end acc)
      (if (> start end)
      acc
      (iter start (- end 1) (cons end acc))
      )
      )

      (iter start end '())
      )

      (define (build-automata needle)
      (define (max-suffix-that-is-prefix str)
      (cond ((string-null? str) "")
      ((not (string-prefix? needle str))
      (max-suffix-that-is-prefix (string-tail str)))
      (else str))
      )

      (define (build-transitions state-string transitions dictionary)
      (if (null? dictionary)
      transitions
      (let* ((c (car dictionary))
      (suffix (max-suffix-that-is-prefix
      (string-append-c state-string c))))
      (build-transitions
      state-string
      (if (string-null? suffix)
      transitions
      (cons (cons c (string-length suffix)) transitions))
      (cdr dictionary))
      )
      )
      )

      ;; Last state does not require a transition as it is the final state.
      ;; "We are done by that point".
      (let ((dictionary (string->list "abcdefghijkmnopqrstuvwxyz")))
      (map (lambda (n)
      (build-transitions (substring needle 0 n) '()
      dictionary))
      (enumerate 0 (- (string-length needle) 1))
      )
      )
      )

      ;; Takes an automata and a string and returns the offset of the pattern the
      ;; automata was built to search
      (define (run-automata automata string)
      (define (search-transition c state-transitions)
      (cond ((null? state-transitions) 0)
      ((char=? (caar state-transitions) c) (cdar state-transitions))
      (else (search-transition c (cdr state-transitions))))
      )

      (define (step state automata-size offset)
      (cond ((= state automata-size)
      (- offset automata-size))
      ((>= offset (string-length string)) #f)
      (else
      (step (search-transition (string-ref string offset)
      (list-ref automata state))
      automata-size
      (+ offset 1))))
      )

      (step 0 (length automata) 0)
      )








      share













      I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The Idea was to use this routines as a mean to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.



      This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.



      NOTES:




      1. I know that using lists might not be the most efficient thing to do but they allowed me to program in a more functional way without using vector-set!


      2. If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.


      3. Sadly emacs uses tabs for indentation so formatting may be a little messy.



      An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to.
      If no pair contains a specific character then it defaults to the invalid state (index = 0).



      the run-automata function searches a matching substring and returns its offset or #f is it is not contained inside string.



      Thanks for you time!



      (define (string-null? s) (= (string-length s) 0))
      (define (string-append-c s c) (string-append s (string c)))
      (define (string-tail str) (substring str 1 (string-length str)))

      ;; is s2 a prefix of s1?
      ;; [TODO] - Use offset instead of string-tail
      (define (string-prefix? s1 s2)
      (cond ((string-null? s2) #t)
      ((string-null? s1) #f)
      ((not (char=? (string-ref s2 0)
      (string-ref s1 0))) #f)
      (else (string-prefix? (string-tail s1)
      (string-tail s2))))
      )

      (define (enumerate start end)
      (define (iter start end acc)
      (if (> start end)
      acc
      (iter start (- end 1) (cons end acc))
      )
      )

      (iter start end '())
      )

      (define (build-automata needle)
      (define (max-suffix-that-is-prefix str)
      (cond ((string-null? str) "")
      ((not (string-prefix? needle str))
      (max-suffix-that-is-prefix (string-tail str)))
      (else str))
      )

      (define (build-transitions state-string transitions dictionary)
      (if (null? dictionary)
      transitions
      (let* ((c (car dictionary))
      (suffix (max-suffix-that-is-prefix
      (string-append-c state-string c))))
      (build-transitions
      state-string
      (if (string-null? suffix)
      transitions
      (cons (cons c (string-length suffix)) transitions))
      (cdr dictionary))
      )
      )
      )

      ;; Last state does not require a transition as it is the final state.
      ;; "We are done by that point".
      (let ((dictionary (string->list "abcdefghijkmnopqrstuvwxyz")))
      (map (lambda (n)
      (build-transitions (substring needle 0 n) '()
      dictionary))
      (enumerate 0 (- (string-length needle) 1))
      )
      )
      )

      ;; Takes an automata and a string and returns the offset of the pattern the
      ;; automata was built to search
      (define (run-automata automata string)
      (define (search-transition c state-transitions)
      (cond ((null? state-transitions) 0)
      ((char=? (caar state-transitions) c) (cdar state-transitions))
      (else (search-transition c (cdr state-transitions))))
      )

      (define (step state automata-size offset)
      (cond ((= state automata-size)
      (- offset automata-size))
      ((>= offset (string-length string)) #f)
      (else
      (step (search-transition (string-ref string offset)
      (list-ref automata state))
      automata-size
      (+ offset 1))))
      )

      (step 0 (length automata) 0)
      )






      scheme





      share












      share










      share



      share










      asked 4 mins ago









      Thomas

      663




      663



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210400%2ffsm-substring-search-on-scheme%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210400%2ffsm-substring-search-on-scheme%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Ellipse (mathématiques)

          Quarter-circle Tiles

          Mont Emei