gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:38:44 24 4
gpt4 key购买 nike

假设我有以下功能:

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 block 中使用此功能,例如
(a,b) <- parse msg :: IO (Int,Int)

在另一个地方,比如
s <- parse msg :: IO String

现在,如果我想让异常更详细地报告它未能读取的类型
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 ++ " as " ++
show ( typeOf something_that_has_type_b))

我如何得到具有 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

但这看起来很傻。

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

最佳答案

您不需要虚拟变量,可以使用 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))

关于Haskell:有没有办法从函数内部推断出函数的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27547824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com