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))