我尝试将函数edits1
应用两次,但在f
的定义中输入“=”时出现解析错误
delete1 :: String -> [String]
delete1 [] = []
delete1 (x:xs) = xs : map (x:) (delete1 xs)
replaced12 :: String -> [String]
replaced12 [] = []
replaced12 (x:xs) = [h c | c <- ['a'..'z']] ++ map (x:) (replaced12 xs)
where h :: Char -> String
h c = c:xs
replaced1 :: String -> [String]
replaced1 a = delete a $ replaced12 a
inserted1 :: String -> [String]
inserted1 [] = []
inserted1 (x:xs) = [ x:c:xs | c <- ['a'..'z']] ++ map (x:) (inserted1 xs)
transposed1 :: String -> [String]
transposed1 (x:y:xs) = (y:x:xs) : map (x:) (transposed1 (y:xs))
transposed1 xs = []
edits1 :: String -> [String]
edits1 a = nub $ (delete1 a ++ replaced1 a ++ inserted1 a ++ transposed1 a)
edits2 :: String -> [String]
edits2 a = nub . f . edits1 a
where f :: [String] -> [String]
f [] = []
f (x:xs) = (edits1 x) ++ map (x:) (f xs)
第一个功能是工作,所以错误必须在2'nd函数中,但我无法弄清楚它是什么。我该如何解决?
答案 0 :(得分:1)
首先,你应该替换:
edits2 a = nub . f . edits1 a
使用:
edits2 a = nub $ f (edits1 a)
其次,您遇到f (x:xs) = (edits1 x) ++ map (x:) (f xs)
:
Couldn't match type ‘[Char]’ with ‘Char’
Expected type: Char
Actual type: String
In the first argument of ‘(:)’, namely ‘x’
In the first argument of ‘map’, namely ‘(x :)’
根据您的定义,x
的类型为String
,而xs
的类型为[String]
(x:)
是一个以[String]
为参数的函数,但map
会尝试将其应用于[String]
String
的每个元素。这不起作用。
评论后修改:
edits2
功能
edits2 :: String -> [String]
edits2 a = nub . f . edits1 a
where f :: [String] -> [String]
f [] = []
f (x:xs) = (edits1 x) ++ map (x:) (f xs)
应替换为此版本:
edits2 :: String -> [String]
edits2 a = nub $ foldl (\acc x -> acc ++ edits1 x) [] (edits1 a)
对edits1 a
的第一次调用将函数应用于参数。然后它使用折叠第二次调用edits1
并连接结果。