Ich möchte eine Zeichenfolge nehmen und in eine Liste von Direction
verwandeln. Beispielsweise sollte "UDDUD"
[U,D,D,U,D]
zurückgeben, während jede Zeichenfolge, die keine U
oder enthält, Nothing
zurückgibt (z. B. "UDYD" gibt Nothing
zurück).Haskell - Maybe und Rekursion
data Direction = U | D
deriving (Show, Eq)
-- where U is Up and D is Down
findDirection :: [Char] -> Maybe [Direction]
findDirection [] = Nothing
findDirection ['U'] = Just [U]
findDirection ['D'] = Just [D]
findDirection (x:xs)
| x == 'U' = Just (U : findDirection xs)
| x == 'D' = Just (D : findDirection xs)
| otherwise = Nothing
ich die folgende Fehlermeldung erhalten:
Couldn't match expected type ‘[Direction]’
with actual type ‘Maybe [Direction]’
In the second argument of ‘(:)’, namely ‘findDirection xs’
In the first argument of ‘Just’, namely
‘(U : findDirection xs)’
Test_findDirection.hs:8:32:
Couldn't match expected type ‘[Direction]’
with actual type ‘Maybe [Direction]’
In the second argument of ‘(:)’, namely ‘findDirection xs’
In the first argument of ‘Just’, namely
‘(D : findDirection xs)’
Wie ich es verstehe, Just (D : findDirection xs)
und Just (U : findDirection xs)
sind vom Typ [Direction]
? Warum ist das der Fall? Was mache ich hier falsch?
'U: findirection xs' (und' D: findDirection xs') ist schlecht typisiert: Man kann eine 'Direction' nicht zu einer' Maybe [Direction] 'machen. Außerdem schreiben Sie: * [...] jeder String, der kein 'U' oder' D' enthält, gibt 'Nothing' zurück (zB' 'UDYD'' gibt 'Nothing' zurück). * Widersprichst du dir nicht selbst, hier ? – Jubobs