I'm in my first few days of learning Haskell and I'm struggle with the Maybe type that is being returned from the Haskell's find function. I defined a function called FindNextState which takes in a tuple, and 2 Strings. This funcition calls getListOfNextStates which uses a lambda and pattern matching to get a list from the passed in tuple and then uses the find function's predicate I find a match in that list. The problem is find returns return a Maybe of my Transition type, this is preventing me from calling my getToState function because it's expecting at Transition. Is there anyway to convert the Maybe returned by find function?
Code
type State = String type Symbol = String type Transisition = (State, Symbol, State) states = ["s0","s1"] initState = "s0" finalStates = ["s3"] transisitionList = [("s0", "0", "s1"), ("s0", "1", "s1")] dfa = (states, initState, finalStates, transisitionList) getToState :: Transisition -> State getToState (_, _, toState) = toState findNextState :: DFA -> State -> Symbol -> Maybe Transisition --Maybe Transisition is the issue, I need it to be my type of Transisition otherwise Haskell throws an error when I load my program findNextState (_,_,_,tList) state symbol = getListOfNextStates tList state symbol getListOfNextStates :: [Transisition] -> State -> Symbol -> Maybe Transisition getListOfNextStates tList state symbol = find(\(sState,sym,eState) -> matchTransition state symbol (sState,sym,eState)) tList Sample Input
findNextState dfa "s2" "0" Just ("s2","0","s3") *Main> :t findNextState dfa "s2" "0" findNextState dfa "s2" "0" :: Maybe Transisition ** Desired Code**
findNextState :: DFA -> State -> Symbol -> State findNextState (_,_,_,tList) state symbol = getToState( (getListOfNextStates tList state symbol) )
Nothingif it doesn't find a match, which is a really good standard way of encoding a failure state. If you wantfindNextStateto returnTransitionthen you need to encode your failure state as aTransitionsomehow (you can't just return a string since that isn't aTransition). If you do that, the failure would be passed togetToStateand processed, as if it was a successful find, which is probably not what you want. Leaving it as aMaybeis probably the preferred option, and you can use a case statement/pattern matching to extract the value.fromJust :: Maybe a -> a. Not recommended in general, but it has its uses.fromJust :: Maybe Transisition-> TransisitionfromJust a = a