<p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p>

<p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p>

<p>I'd like to understand how such an algorithm would be coded in a functional language.  How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms.  Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>

[{'answer_id': 46948, 'author': 'Rob Rolnick', 'author_id': 4798, 'author_profile': 'https://Stackoverflow.com/users/4798', 'pm_score': 0, 'selected': False, 'text': '<p>I imagine you\'d want something like a tree with a list of children, as described <a href="http://csus.cs.mcgill.ca/wiki/COMP-302_(Panangaden%2C_Pientka%2C_Winter_06)_Lectures#Trees_with_a_list_of_children" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 47002, 'author': 'Thomas Kammeyer', 'author_id': 4410, 'author_profile': 'https://Stackoverflow.com/users/4410', 'pm_score': 3, 'selected': True, 'text': '<p>I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup.  Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):</p>\n\n<pre><code>(defun buildtree (wordlist) ...code to build tree recursively returns the tree...)\n(define lookup (tree word) ...code to look up word using tree, returns t or nil...)\n\n(defun lookupmany (tree querylist)\n   (if (eq querylist nil)\n       nil\n       (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist))\n   )\n)\n\n(defun main (wordlist querylist) ; the main entry point\n   (lookupmany (buildtree wordlist) querylist)\n)\n</code></pre>\n\n<p>if this is what you mean, this is fairly straight-forward functional programming.\nIs it really stateless?  That\'s a matter of debate.  Some people would say some\nforms of functional programming store what we normally call "state" on the stack.\nMoreover, Common LISP even since the first edition of the Steele book has had iterative\nconstructs, and LISP has had setq for a long, long time.</p>\n\n<p>But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here.</p>\n\n<p>I think the above is something like the arrangement you mean.</p>\n'}]
['https://Stackoverflow.com/questions/46924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4177/']