从Haskell中的字符串中推断出类型
我正在研究Haskell中的JSON数据编码器! (更具体地说,我正在尝试移植 jo 到haskell!)。我已经有很多工作,但是我遇到了一些皱纹。我会在这里努力简化我的问题,我试图剥夺尽可能多的不需要的上下文。
目标:构建value
给定的字符串
。
这些字符串来自命令行:用户以< key> =< value>
的形式输入键/值对。将它们分开后,我被留在一个String
中,即未知类型的值数据。
示例案例:
let s = "someString" -- use the `String` constructor
let s = "1234" -- use the `Number` constructor
let s = "True" -- use the `Bool` constructor
问题:如何推断s
的内容是String
vs a numbern
,bool
/code>等?
这是Aeson value
type的相关类型 +构造函数(编辑为简短)。
data Value = Object Object
| Array Array
| String Text
| Number Scientific
| Bool Bool
| Null
I'm working on a JSON data encoder in Haskell! (to be more specific, I am trying to port Jo into Haskell!). I've gotten a lot of it working, but I'm running into a little wrinkle. I'll try to be concise with my question here, I've tried to strip away as much unneeded context as possible.
Goal: Construct a Value
given a String
.
These strings come from the command line: Users enter in key/value pairs in the form <key>=<value>
. After splitting them apart I am left in a String
that is the value data of unknown type.
Example cases:
let s = "someString" -- use the `String` constructor
let s = "1234" -- use the `Number` constructor
let s = "True" -- use the `Bool` constructor
Question: How might I infer that the contents of s
is a String
vs a Number
, Bool
, etc?
This is the relevant type + constructors for the Aeson Value
type (edited for brevity).
data Value = Object Object
| Array Array
| String Text
| Number Scientific
| Bool Bool
| Null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您已经在使用 aeson 软件包,因此可以使用 decode 。之所以起作用,是因为
value
也是bytestring
实例:注意(如n。1.8e9-mys-my-share m。在评论)必须引用字符串。
那么,您可以做的是将您的未知价值拿出来,并首先用引号包围,并试图解析它。然后尝试在没有周围的引号的情况下再次解析它。
现在,您有两个
也许值
值。选择第一个仅
值(并准备处理nothing
案例)。Since you're already using the aeson package, you could use decode. This works because
Value
is also aByteString
instance:Notice (as n. 1.8e9-where's-my-share m. points out in the comments) that strings must be quoted.
What you could do, then, is to take your unknown value and first surround it with quotes and attempt to parse it. Then try to parse it again without surrounding quotes.
You now have two
Maybe Value
values. Pick the firstJust
value (and be prepared to deal with theNothing
case).