Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell:有没有办法从函数内部推断函数的返回类型?_Haskell_Types_Polymorphism_Return Value - Fatal编程技术网

Haskell:有没有办法从函数内部推断函数的返回类型?

Haskell:有没有办法从函数内部推断函数的返回类型?,haskell,types,polymorphism,return-value,Haskell,Types,Polymorphism,Return Value,假设我有以下函数: import Data.Typeable import Text.Read (reads) parse :: (Read b, Typeable b) => String -> IO b parse msg = case reads msg of [(value,"")] -> return value _ -> throwIO $ ErrorCall ("could not parse " ++ msg) 它将字符

假设我有以下函数:

import Data.Typeable
import Text.Read (reads)

parse :: (Read b, Typeable b) => String -> IO b
parse msg = case reads msg of
        [(value,"")] -> return value
        _ -> throwIO $ ErrorCall ("could not parse " ++ msg)
它将字符串解析为我想要的任何内容。 如果字符串格式不正确,它将抛出一个异常,显示无法解析的消息

我在IO Monad的do块中使用此函数

(a,b) <- parse msg :: IO (Int,Int)
我怎样才能得到b型的东西

一个可能的解决办法是这样做

import Data.Typeable
import Text.Read (reads)

parse :: (Read b, Typeable b) => b -> String -> IO b
parse dummy msg = case reads msg of
        [(value,"")] -> return value
        _ -> throwIO $ ErrorCall ("could not parse " ++ msg ++ " as " ++
                         show ( typeOf dummy))
像这样调用它

s <- parse "" msg :: IO String

s您不需要伪变量,可以使用
ScopedTypeVariables
扩展名

{-# LANGUAGE ScopedTypeVariables #-}

parse :: forall b. (Read b, Typeable b) => String -> IO b
parse msg = case reads msg of
    [(value,"")] -> return value
    _ -> error $ "could not parse " ++ msg ++ " as " ++
                     show (typeOf (undefined :: b))

似乎现在所有的酷孩子都在用
Proxy
而不是
undefined
来做这类事情。@dfeuer是的,这是正确的。当
Proxy
现在在
base
中时,使用
undefined
是很遗憾的。是的,现代的方式是
show(typeRep(Proxy::Proxy b))
。而更现代的方式(还没有合并到ghc中)是
show(typeRep(::b))
@augustss:它超越了“现代”和“前卫”;)。不过看起来很棒。另外:如果您希望在请求时返回特定类型的值,并且如果请求未处理的返回类型时出现错误,该怎么办?
s <- parse "" msg :: IO String
{-# LANGUAGE ScopedTypeVariables #-}

parse :: forall b. (Read b, Typeable b) => String -> IO b
parse msg = case reads msg of
    [(value,"")] -> return value
    _ -> error $ "could not parse " ++ msg ++ " as " ++
                     show (typeOf (undefined :: b))