()在Haskell函数签名中的含义是什么?

时间:2016-05-21 23:37:19

标签: haskell

我的Haskell文件中有以下函数:

notFound :: () -> IO ()
notFound = putStr "Sorry, your command could not be found"

该功能无法编译。这是我得到的编译错误:

todos.hs:27:12:
    Couldn't match expected type ‘() -> IO ()’ with actual type ‘IO ()’
    Possible cause: ‘putStr’ is applied to too many arguments
    In the expression: putStr "Sorry, your command could not be found"
    In an equation for ‘notFound’:
        notFound = putStr "Sorry, your command could not be found"

但是以下功能可以:

    notFound :: IO ()
    notFound = putStr "Sorry, your command could not be found"

问题:

根据我对类型签名的理解,看起来它们是相同的,()意味着没有参数传递给函数。那不是这样吗?如果不是,那么函数签名中的()是什么意思呢?

2 个答案:

答案 0 :(得分:4)

()是空元组。它不是什么都没有,它更像是C语言中的void类型或长度为零的固定长度列表。与() :: ()类似,只有一个类型为Bool的对象。

为什么会这样?一般来说,我已经看到它过去常常关闭"类型中的一个变量。因此IO ()IO操作,它始终返回相同的内容:()

一个可能更好的例子是:Conduit a IO b需要一些类型a对象的流,并将其转换为b个对象的流。但是如果你有什么东西不接受输入流怎么办?您可以将其表示为Conduit () IO b至"关闭"输入流。 (我这里的定义松散而快速,但我认为它或多或少都有效)

答案 1 :(得分:1)

您的from mpi4py import MPI 函数定义的函数采用类型notFound的值,并返回类型()的值。 IO()()类型的唯一值。你的功能是无意识的无点符号

()

相当于

notFound :: () -> IO ()
notFound = putStr "Sorry, your command could not be found"

这显然不起作用,因为函数notFound :: () -> IO () notFound () = putStr "Sorry, your command could not be found" () 不接受putStrLn作为第二个参数。

您当然可以将其定义为

()

这会编译,但是相当荒谬,因为它需要作为notFound :: () -> IO () notFound () = putStr "Sorry, your command could not be found" 调用。

你真正想要的只是IO动作,而不是功能。因此,您可以将其定义为notFound ()

相关问题