简体   繁体   English

从 Haskell 中的字符串推断类型

[英]Infer a type from a string in Haskell

I'm working on a JSON data encoder in Haskell!我正在使用 Haskell 开发 JSON 数据编码器! (to be more specific, I am trying to port Jo into Haskell!). (更具体地说,我正在尝试将Jo移植到 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 .目标:构造一个给定StringValue

These strings come from the command line: Users enter in key/value pairs in the form <key>=<value> .这些字符串来自命令行:用户以<key>=<value>的形式输入键/值对。 After splitting them apart I am left in a String that is the value data of unknown type.将它们分开后,我留在了一个String中,它是未知类型的值数据。

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?问题:我如何推断s的内容是StringNumberBool等?

This is the relevant type + constructors for the Aeson Value type (edited for brevity).这是 Aeson Value类型的相关类型 + 构造函数(为简洁起见进行了编辑)。

data Value = Object Object
           | Array Array
           | String Text
           | Number Scientific
           | Bool Bool
           | Null

Since you're already using the aeson package, you could use decode .由于您已经在使用aeson包,您可以使用decode This works because Value is also a ByteString instance:这是有效的,因为Value也是一个ByteString实例:

Prelude Data.Aeson> decode "\"someString\"" :: Maybe Value
Just (String "someString")
Prelude Data.Aeson> decode "1234" :: Maybe Value
Just (Number 1234.0)
Prelude Data.Aeson> decode "true" :: Maybe Value
Just (Bool True)

Notice (as n. 1.8e9-where's-my-share m. points out in the comments) that strings must be quoted.请注意(正如n. 1.8e9-where's-my-share m.在评论中指出的那样)必须引用字符串。

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.您现在有两个Maybe Value值。 Pick the first Just value (and be prepared to deal with the Nothing case).选择第一个Just值(并准备处理Nothing情况)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM