-2

I have to make a state machine, which equals a text editor's search funtion.

I need to use foldl/foldr to apply the function to every character of a string.

I have a few states, which I have to work with:

type State = Int

start :: State
start = 0

accept :: State
accept = (-2)

reject :: State
reject = (-1)

And I have type synonim : type Definition = [(State, Char -> State)]

The function should look like this: fsm :: Definition -> String -> Bool

My code looks like this right now:

transition :: Char -> State -> (Char -> State)

transition x y z
 | x == z = y
 | x == '*' = y
 | otherwise = reject

transitions :: [(Char, State)] -> (Char -> State)

transitions ((a,b):xs) e 
 | a == e || a == '*' = b
 | a /= e || a /= '*' = transitions xs e
 | otherwise = reject


step :: Definition -> State -> Char -> State

step ((a,b):xs) e f
 | a == e = b f
 | a /= e = step xs e f
 | otherwise = reject

It has a starting state, apply transition or transitions function and if it is accepted, the state accepted is the next starting state.

Here is some test cases, which I have to test the function:

fsm [ (start, transition '*' accept)] "x" == True

fsm [ (start, transition 'a' 1)
    , (1, transition 'l' 2)
    , (2, transition '*' accept)
    ] "alma" == True

fsm [ (start, transition '*' 1)
    , (1, transition '*' 2)
    , (2, transition 'x' 3)
    , (3, transition '*' accept)
    ] "taxi" == True

fsm [ (start, transitions [('\n',accept), ('*', 1)])
    , (1, transition '*' start) 
    ] "aa\n" == True
  • 2
    What is your question? – Willem Van Onsem May 17 '19 at 20:57
  • How to write the fsm function with foldl or foldr – xentaquadrin May 17 '19 at 21:05
  • 7
    It is your responsibility to attempt this goal. If you find that your approaches do not work, and *even after trying very hard* cannot figure out why, then outline what approach you took, what you expected the outcome of that approach to be and why, and what the outcome actually was. (If the actual outcome is a compiler error, then the correct way to communicate it is to copy and paste the complete error into your question.) Then we can help you identify the flaw in your reasoning. – Daniel Wagner May 17 '19 at 21:43

1 Answers1

0

If you fill in the initial state and the string to process in foldl, the types basically imply the rest:

-- foldl :: Foldable t => (State -> Char -> State) -> State -> [Char] -> State
fsm def str = foldl x start str

Here x must have type State -> Char -> State and give you the next state given the current one and the next character, which is what your step function does given a Definition that you have. This gives you:

fsm def str = foldl (step def) start str :: State

Now you have a State but need a Bool saying if it's accepted, which is just a simple comparison:

fsm def str = foldl (step def) start str == accept
that other guy
  • 116,971
  • 11
  • 170
  • 194