Haskell中的类型安全的"read" [英] Type-safe `read` in Haskell

查看:55
本文介绍了Haskell中的类型安全的"read"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

了解Haskell 讨论以下数据类型:

Learn You a Haskell discusses the following data type:

data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday   
           deriving (Eq, Ord, Show, Read, Bounded, Enum)  

这本书演示了如何使用 read 将String解析为 Day 类型.

The book demonstrates how to use read to parse a String into a Day type.

$ read "Saturday" :: Day
Saturday

但是,我可以传递非Day值,从而导致异常.

However, I can pass in a non-Day value, resulting in an exception.

$ read "foo" :: Day
*** Exception: Prelude.read: no parse

在上面的示例中,使用 read 的类型安全的方法是什么?

What's a type-safe way to use read in the above example?

推荐答案

除了@JonPurdy提到的旧标准函数 reads 外,还有最近添加的

In addition to the old standard function reads mentioned by @JonPurdy, there's also the more recently added

Text.Read.readMaybe :: Read a => String -> Maybe a

当字符串仅包含一个要解析的值时,使用起来更简单.

which is simpler to use when the string contains just one value to parse.

这篇关于Haskell中的类型安全的"read"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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