Gue*_*OCs -1 io haskell types typeclass type-signature
我正在从这里做一些 Haskell 练习:https : //wiki.haskell.org/99_questions/Solutions/1,它显示了解决方案,但没有显示如何打印结果
我试过
myLast :: [a] -> IO ()
myLast [] = error "No end for empty lists!"
myLast [x] = print x
myLast (_:xs) = myLast xs
main :: IO ()
main = myLast [1,2,3]
Run Code Online (Sandbox Code Playgroud)
我有
/workspaces/hask_exercises/exercises/src/Lib.hs:10:14: error:
* No instance for (Show a) arising from a use of `print'
Possible fix:
add (Show a) to the context of
the type signature for:
myLast :: forall a. [a] -> IO ()
* In the expression: print x
In an equation for `myLast': myLast [x] = print x
Run Code Online (Sandbox Code Playgroud)
如何打印最后一个元素?
我认为列表中元素的类型必须实现Show
,但我不知道如何强制执行。
要求列表元素所属的方法Show
是将该约束添加到类型签名:
myLast :: Show a => [a] -> IO ()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56 次 |
最近记录: |