Haskell:I / O和从函数返回 [英] Haskell: I/O and Returning From a Function

查看:164
本文介绍了Haskell:I / O和从函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请耐心等待我,因为我对函数式编程和Haskell都很陌生。我试图在Haskell中编写一个函数,它接受一个I​​ntegers列表,打印所述列表的头部,然后返回列表的尾部。该函数需要是[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)

我怀疑点函数中打印的调用是导致的推断类型为IO [a]。有什么方法可以忽略打印的返回类型,因为我需要返回的是列表的尾部被传递到点。

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


  1. [Int] - > [Int] 未执行任何IO或

  2. [Int] - > IO [Int] with IO

  1. [Int] -> [Int] without performing any IO or
  2. [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和从函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆