diff options
Diffstat (limited to 'edit-lens/src/Data/String/DFST.hs')
-rw-r--r-- | edit-lens/src/Data/String/DFST.hs | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/edit-lens/src/Data/String/DFST.hs b/edit-lens/src/Data/String/DFST.hs new file mode 100644 index 0000000..8a22dd3 --- /dev/null +++ b/edit-lens/src/Data/String/DFST.hs | |||
@@ -0,0 +1,38 @@ | |||
1 | {-# LANGUAGE RecordWildCards | ||
2 | , PatternGuards | ||
3 | , ScopedTypeVariables | ||
4 | #-} | ||
5 | |||
6 | {-| | ||
7 | Description: Deterministic finite state transducers | ||
8 | -} | ||
9 | module Data.String.DFST | ||
10 | ( DFST(..) | ||
11 | , runDFST | ||
12 | ) where | ||
13 | |||
14 | import Data.Map.Strict (Map, (!?)) | ||
15 | import qualified Data.Map.Strict as Map | ||
16 | |||
17 | import Data.Set (Set) | ||
18 | import qualified Data.Set as Set | ||
19 | |||
20 | data DFST state = DFST | ||
21 | { stInitial :: state | ||
22 | , stTransition :: Map (state, Char) (state, Maybe Char) | ||
23 | -- ^ All @(s, c)@-combinations not mapped are assumed to map to @(s, Nothing)@ | ||
24 | , stAccept :: Set state | ||
25 | } | ||
26 | |||
27 | runDFST :: forall state. Ord state => DFST state -> String -> Maybe String | ||
28 | runDFST DFST{..} str = ($ []) <$> go stInitial str id | ||
29 | where | ||
30 | go :: state -> String -> (String -> String) -> Maybe (String -> String) | ||
31 | go st [] acc | ||
32 | | st `Set.member` stAccept = Just acc | ||
33 | | otherwise = Nothing | ||
34 | go st (c:cs) acc | ||
35 | | Just (st', mc') <- stTransition !? (st, c) | ||
36 | = go st' cs $ acc . maybe id (:) mc' | ||
37 | | otherwise | ||
38 | = go st cs acc | ||