无法与实际类型匹配的预期类型
我是一个Haskell noob总计,我希望有人能够帮助我,因为我已经在这里呆了几个小时,而且我只知道我正在做一些荒唐可笑的事情。无法与实际类型匹配的预期类型
程序应该扫描字典文件,以确定删除空格的句子集合的所有有效单词序列。
Ex。 “insidewaysoften”可以被分解为“经常侧向”,“内部方式软化”等。
我在python中编写了我的原型,它工作得很好(正如我的Java实现一样),但是课程要求一个Haskell的实现,我不能得到它的工作。提前道歉的罪行我犯有危害的语言和GHC用下面的代码:
import System.Environment
main = do
[dictFilename,sentFilename] <- getArgs
dictFile <- readFile dictFilename
sentFile <- readFile sentFilename
mapM (\sentence -> solve "" "" sentence (words dictFile)) (words sentFile)
solve prefix header [] dict =
if (header `elem` dict)
then return prefix ++ header
else return ""
solve prefix header sent dict = do
let more = solve prefix (header ++ (take 1 sent)) (drop 1 sent) dict
if (header `elem` dict)
then return (solve (prefix ++ header ++ " ") "" sent dict) ++ more
else return more
当调查类错误就是写下的功能类型的签名,你知道的第一件事。
在此,解决可具有型
solve :: String -> String -> String -> [String] -> String
或
solve :: String -> String -> String -> [String] -> IO String
取决于它是否应该有任何副作用而计算的值。看到你在全国各地使用mapM
和return
,我想IO
版本可能已经打算。
现在,如果您记下签名,您将开始获得更有意义的错误消息。例如,而不是这样的:
tmp.hs:19:16:
Couldn't match expected type `Char' with actual type `[Char]'
Expected type: [Char]
Actual type: [[Char]]
In the return type of a call of `solve'
In the first argument of `return', namely
`(solve (prefix ++ header ++ " ") "" sent dict)'
,这并没有太大的意义,你会得到这样的:
tmp.hs:14:8:
Couldn't match expected type `IO String' with actual type `[a0]'
In the expression: return prefix ++ header
In the expression:
if (header `elem` dict) then return prefix ++ header else return ""
In an equation for `solve':
solve prefix header [] dict
= if (header `elem` dict) then
return prefix ++ header
else
return ""
,这正好说明了问题的所在。函数应用程序在Haskell中的优先级最高,所以return prefix ++ header
等于(return prefix) ++ header
,这绝对不是你的意思。
顺便说一句,如果我从返回类型中删除IO
,请删除所有return
s并通过添加putStrLn
来更改调用,代码将编译并运行!唯一的问题是它将所有可能的句子连接成一个单独的字符串而没有任何分隔。
谢谢!这正是我一直期待的答复。 :) – dpiers 2011-05-02 04:59:31
那么它有什么问题?你会得到什么错误?哪里? – Gabe 2011-05-02 03:18:09
你是否偶然采取与MeeksMan13相同的课程,他写了[这个问题](http://stackoverflow.com/questions/5852841/splitting-a-sentence-without-any-whitespace-seperators-into-a-tencetence -with白色)?另外,是的,这是否会产生错误,还是只是不正确?如果是这样,它以什么方式失败? – 2011-05-02 03:25:35
是的,杰弗里,我看起来和MeeksMan13一样。在我发布我的信息后,我看到了他的问题。我发布的代码是返回类型错误,例如Rotsor在他的帖子中显示的错误,我认为根据他提供的信息我会很好。 – dpiers 2011-05-02 04:57:24