type Pattern = [PatternPart]
data PatternPart =
MatchTuple [PatternPart] |
Named String |
MatchAny
data ArguementIndex =
InTuple Int ArguementIndex | -- arguement is in tuple at index Int, then at index...
ArgIndex Int
testPattern = [Any, MatchTuple[Any, Named "hello"]]
getArgIndex :: Pattern -> String -> Maybe ArguementIndex
我需要编写一个函数getArgIndex
来搜索testPattern
"hello"
并返回InTuple 1 (ArgIndex 1)
getArgIndex [Any, Any, MatchTuple [Named "hi"]] "hi" = Just (InTuple 2 (ArgIndex 0))
另一个例子
我无法想出一个优雅的方法来做到这一点。
请告知。
答案 0 :(得分:1)
你怎么知道只有一场比赛?
尝试这样的事情:
import Data.Maybe (listToMaybe)
getArgIndex :: Pattern -> String -> Maybe ArguementIndex
getArgIndex haystack needle = listToMaybe (getArgIndices haystack needle)
getArgIndices :: Pattern -> String -> [ArguementIndex]
getArgIndices haystack needle
= concat $ zipWith f [0..] haystack
where f i (MatchTuple haystack') = map (InTuple i) $ getArgIndices haystack' needle
f i (Named item) | item == needle = [ArgIndex i]
f i _ = []
(未经测试。)如果有多个匹配,则假设您想要第一个匹配。
(您需要使用“参数”的正确拼写。)
就个人而言,如果可以的话,我会把论点按相反的顺序排列:
getArgIndices' :: String -> Pattern -> [ArguementIndex]
getArgIndices' needle = g
where g = concat . zipWith f [0..]
f i (MatchTuple haystack) = map (InTuple i) $ g haystack
f i (Named item) | item == needle = [ArgIndex i]
f i _ = []