首页 > 解决方案 > 如何在 Haskell 中打印列表的最后一个元素?

问题描述

我正在从这里做一些 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]

我有

/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

如何打印最后一个元素?

我认为列表中元素的类型必须以某种方式实现Show,但我不知道如何强制执行。

标签: haskelltypesiotypeclasstype-signature

解决方案


要求列表元素所属的方法Show是将该约束添加到类型签名中:

myLast :: Show a => [a] -> IO ()

推荐阅读