对haskell的类型系统,还有一个困惑。
haskell是静态类型,所以会有这样一个问题
class A t where
funA :: t -> IO ()
instance A W where
funA w = do
bluh w
return ()
...
wList :: (A a) => [a]
...
main = do
mapM_ (funA) wList
最后一行编译无法通过。
怎么办?
[ 本帖最后由 Magicloud 于 2009-6-30 15:35 编辑 ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
a <- widgetRun widget中widget的类型不能确定, 改成: a <- widgetRun widget::你的类型
1 main = do
2 mapM_ ((x, y, widget) -> do
3 a <- widgetRun widget
4 putStrLn $ show a
5 ) widgetList
6
7 widgetList :: (Widget w) => [(Integer, Integer, w)]
8 widgetList = []
9
10 class Widget w where
11 widgetRun :: w -> IO ()
---
% ghc --make tmp/test.hs
[1 of 1] Compiling Main ( tmp/test.hs, /tmp/Main.o )
tmp/test.hs:3:16:
Ambiguous type variable `t' in the constraint:
`Widget t' arising from a use of `widgetRun' at tmp/test.hs:3:16-31
Probable fix: add a type signature that fixes these type variable(s)
看不到完整的代码,就不可能知道问题出在什么地方。
那就郁闷了……想用class表现几个data的共性,怎么办呢?
在 widgetList 的类型声明中,w 需要更多的限定。
Main.hs:28:40:
Ambiguous type variable `t' in the constraint:
`W.Widget t'
arising from a use of `W.widgetRun' at Main.hs:28:40-57
Probable fix: add a type signature that fixes these type variable(s)
---
25 main = do
26 prs <- newEmptyMVar
27 prs_ <- foldM (prs_ (x, y, widget) -> do
28 pid <- forkProcess $ W.widgetRun widget
29 return $ M.insert pid (x, y, fst $ W.widgetNew widget, snd $ W.widgetNew widget) prs_
30 ) M.empty widgetList
...
84 widgetList :: (W.Widget w) => [(Integer, Integer, w)]
85 widgetList = []
...
1 module Widget where
2
3 class Widget w where
4 widgetNew :: w -> (Integer, Integer)
5 widgetRun :: w -> IO ()
我把你顶楼的代码补全后,可以编译通过。
完整的代码和编译错误信息,直接拷贝粘贴。
基本代码就是类似的了,但A的instance有多个。当wList可能返回[]时,编译不通过。错误是funA不能确定参数类型(这时候mapM_根本不会执行呀!)。
出了什么错误?给个完整的例子看看。