Function 如何在Haskell中像python或scala一样运行print?

Function 如何在Haskell中像python或scala一样运行print?,function,haskell,Function,Haskell,我尝试在Haskell中打印函数只是为了好玩,例如: {-# LANGUAGE FlexibleInstances #-} instance Show (Int -> Bool) where show _ = "function: Int -> Bool" 在GHCi中加载并运行,示例: λ> :l foo [1 of 1] Compiling Main ( foo.hs, interpreted ) foo.hs:2:1: Warning

我尝试在Haskell中打印函数只是为了好玩,例如:

{-# LANGUAGE FlexibleInstances #-}

instance Show (Int -> Bool) where
    show _ = "function: Int -> Bool"
在GHCi中加载并运行,示例:

λ> :l foo
[1 of 1] Compiling Main             ( foo.hs, interpreted )

foo.hs:2:1: Warning: Unrecognised pragma
Ok, modules loaded: Main.
λ> (==2) :: Int -> Bool
function: Int -> Bool

但是,我希望看到每个函数在调用时打印自己。

我假设您希望
show
方法打印函数的地址,这就是Python所做的:

>>> def foo(a):
...     return a
... 
>>> print foo
<function foo at 0xb76f679c>
测试:

$ ./Main 
<function ??? at 804cf90>
$。/Main

不幸的是,没有办法获得函数名,因为它根本不存在于已编译的可执行文件中(可能有调试信息,但不能指望它的存在)。如果你的函数可以从C中调用,你也可以通过使用C助手来获取它的地址。

对于一个普通的函数,你不能有这样的地址,因为类型信息只在编译时出现,但是如果类型是
可键入的
类的一个实例,你可以使用
可键入的
类来编写足够接近的内容

import Data.Typeable

instance (Typeable a, Typeable b) => Show (a -> b) where
    show f = "Function: " ++ (show $ typeOf f)
在ghci中测试此功能

*Main> (+)
Function: Integer -> Integer -> Integer
*Main> (+10)
Function: Integer -> Integer
但在将类型限制为具有
Typeable
实例的类型之前,这不适用于一般函数

*Main> zip

<interactive>:3:1:
    Ambiguous type variable `a0' in the constraint:
      (Typeable a0) arising from a use of `print'
    Probable fix: add a type signature that fixes these type variable(s)
    In a stmt of an interactive GHCi command: print it

<interactive>:3:1:
    Ambiguous type variable `b0' in the constraint:
      (Typeable b0) arising from a use of `print'
    Probable fix: add a type signature that fixes these type variable(s)
    In a stmt of an interactive GHCi command: print it
*Main> zip :: [Int] -> [Bool] -> [(Int,Bool)]
Function: [Int] -> [Bool] -> [(Int,Bool)]
*Main>zip
:3:1:
约束中不明确的类型变量“a0”:
(可打印a0)因使用“打印”而产生
可能修复:添加修复这些类型变量的类型签名
在交互式GHCi命令的stmt中:打印它
:3:1:
约束中不明确的类型变量“b0”:
(可打字b0)因使用“print”而产生
可能修复:添加修复这些类型变量的类型签名
在交互式GHCi命令的stmt中:打印它
*Main>zip::[Int]->[Bool]->[(Int,Bool)]
函数:[Int]->[Bool]->[(Int,Bool)]

您拼写的
语言不正确。谢谢@bisserlis,更正。
*Main> zip

<interactive>:3:1:
    Ambiguous type variable `a0' in the constraint:
      (Typeable a0) arising from a use of `print'
    Probable fix: add a type signature that fixes these type variable(s)
    In a stmt of an interactive GHCi command: print it

<interactive>:3:1:
    Ambiguous type variable `b0' in the constraint:
      (Typeable b0) arising from a use of `print'
    Probable fix: add a type signature that fixes these type variable(s)
    In a stmt of an interactive GHCi command: print it
*Main> zip :: [Int] -> [Bool] -> [(Int,Bool)]
Function: [Int] -> [Bool] -> [(Int,Bool)]