我尝试两次应用函数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)
最佳答案
首先,您应该替换:
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
并连接结果。
https://stackoverflow.com/questions/26951987/