与monadic结果进行模式匹配? [英] Pattern matching against monadic result?

查看:90
本文介绍了与monadic结果进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  readHex :: Num 

我学习Haskell并希望使用readHex a =>阅读a

您如何从这样的函数中提取结果?什么是最常见的方式,对正确的构造函数进行模式匹配,即[(a,)] ??

LiftM和一般的提升似乎是有道理的,但是在解开monadic堆栈时,我却迷失了方向。

解决方案

要回答一般性问题的一般问题,从数据构造函数中提取值的 only 方式是模式匹配。某些数据类型带有为您提取值的函数,但这些函数本身是通过模式匹配实现的,或者调用其他函数,即& c。像 Data.Map.Map IO 这样的抽象数据类型,要隐藏它们的内部结构,仍然需要模式匹配跟...共事;不同之处在于它们不会从定义它们的模块中导出它们的构造函数,所以您只需使用模块中定义的其他函数以及它们提供的操作。



要回答具体问题, ReadS 被定义为

 类型ReadS a = String  - > [(a,String)] 

所以它只是一个类型的同义词。你不需要从 ReadS 本身提取任何东西,它只是一个简写或别名。实际的类型是 [(a,String)] ,你可以像使用列表,元组, String s,等等。



此外, ReadS 不是单子。它是一个不是 Monad 实例的类型的同义词,事实上它不能直接制成一个(没有办法写 [(a,String)] 以实例声明所需的格式)。


I am learning Haskell and want to use "readHex", which according to Hoogle has type:

readHex :: Num a => ReadS a

How do you "extract" a result from such a function? What's the most common way, pattern match against the right constructor ie, [(a,"")] ??

LiftM and lifting in general seems to make some sense, but I'm lost when it comes to "unwinding" the monadic stack.

解决方案

To answer the general question in general terms, the only way to extract values from a data constructor is pattern matching. Some data types come with functions that extract values for you, but those functions are themselves implemented with pattern matching, or call other functions that are, &c. Abstract data types like Data.Map.Map or IO, that want to hide their internal structure, still require pattern matching to work with; the difference is that they don't export their constructors from the module that defines them, so all you have to work with are other functions defined in the module and the operations they provide.

To answer the specific question, ReadS is defined as such:

type ReadS a = String -> [(a, String)]

So it's just a type synonym. You don't need to extract anything from the ReadS itself, it's just a shorthand or alias. The actual type is [(a, String)], which you can work with the same way you would anything else using lists, tuples, Strings, and so on.

Furthermore, ReadS is not a Monad. It's a type synonym for something that isn't a Monad instance, and in fact can't be made into one directly (there's no way to write [(a, String)] in the form required for an instance declaration).

这篇关于与monadic结果进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆