问题描述
请耐心等待,因为我对函数式编程和 Haskell 非常陌生.我试图在 Haskell 中编写一个函数,它接受一个整数列表,打印所述列表的头部,然后返回列表的尾部.该函数需要是 [Integer] -> [Integer] 类型.为了提供一些上下文,我正在编写一个解释器,当在关联列表中查找其各自的命令时调用该函数(键是命令,值是函数).
Please bear with me as I am very new to functional programming and Haskell. I am attempting to write a function in Haskell that takes a list of Integers, prints the head of said list, and then returns the tail of the list. The function needs to be of type [Integer] -> [Integer]. To give a bit of context, I am writing an interpreter and this function is called when its respective command is looked up in an associative list (key is the command, value is the function).
这是我写的代码:
dot (x:xs) = do print x
return xs
编译器给出以下错误信息:
The compiler gives the following error message:
forth.hs:12:1:
Couldn't match expected type `[a]' against inferred type `IO [a]'
Expected type: ([Char], [a] -> [a])
Inferred type: ([Char], [a] -> IO [a])
In the expression: (".", dot)
我怀疑 dot 函数中的打印调用是导致推断类型为 IO [a] 的原因.有什么办法可以忽略打印的返回类型,因为我需要返回的只是传递给 dot 的列表尾部.
I suspect that the call to print in the dot function is what is causing the inferred type to be IO [a]. Is there any way that I can ignore the return type of print, as all I need to return is the tail of the list being passed into dot.
提前致谢.
推荐答案
在大多数函数式语言中,这都行得通.然而,Haskell 是一种纯函数式语言.函数中不允许做IO,所以函数可以是
In most functional languages, this would work. However, Haskell is a pure functional language. You are not allowed to do IO in functions, so the function can either be
[Int] ->[Int]
不执行任何 IO 或[Int] ->IO [Int]
带 IO
[Int] -> [Int]
without performing any IO or[Int] -> IO [Int]
with IO
编译器推断出的dot
的类型是dot :: (Show t) =>[t] ->IO [t]
但您可以将其声明为 [Int] ->IO [Int]
:
The type of dot
as inferred by the compiler is dot :: (Show t) => [t] -> IO [t]
but you can declare it to be [Int] -> IO [Int]
:
dot :: [Int] ->IO [Int]
参见 IO monad:http://book.realworldhaskell.org/read/io.html
See IO monad: http://book.realworldhaskell.org/read/io.html
我没有提到 System.IO.Unsafe.unsafePerformIO
应该非常小心地使用它,并充分了解其后果.
I haven't mentioned System.IO.Unsafe.unsafePerformIO
that should be used with great care and with a firm understanding of its consequences.
这篇关于Haskell:I/O 和从函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!