haskell - 应用函数两次编译错误Haskell

我尝试两次应用函数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的类型为Stringxs的类型为[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/

相关文章:

android - 关于主要 Activity : 'illegal start of expres

objective-c - 隐式转换为NSIndexPath的错误

c# - 如何从 C# 中的封闭构造类中获取基类对象

compiler-errors - 编译示例Scalapack应用程序时出现问题

c# - 抑制ASPX文件的生成错误

compiler-errors - opencl编译错误

compiler-errors - 无法解决错误,VHDL,语法错误,但我看不到

maven - 执行失败 : 'control build' & Failed to execute

compiler-errors - Latex中缺少\begin {document}

c#-4.0 - 为什么我的变量在分配时说未分配?