繁体   English   中英

如何使用PureScript向用户显示任何数据类型?

[英]How do you present any data type to the user with PureScript?

我想创建一个非常人性化的开发环境,我正在考虑使用PureScript来提供语言部分。 我看到开箱即用, Show不能用于Show实例记录:

log (show {a:5})

'试试PureScript!' http://try.purescript.org/ )编译器说:

   No type class instance was found for

   Prelude.Show { a :: Int
                }

是否有用于一般打印任何数据结构的工具,尤其是包含记录的数据结构? 是否有一些类型的技巧可以支持一般走过记录来支持我自己的类,如present :: Present a => a -> Presentation 问题是我不知道提前的类型是什么。 用户输入记录,我希望能够呈现它。 似乎我必须修补编译器以支持这一点。

实例头中不允许记录。 出于讨论和原因,请参阅此主题 。如果我们想为它们编写实例,则必须将它们包装在datanewtype

但是,有一个泛型库和一个派生机制,可以让我们生成Show实例。

import Data.Generic

data Foo = Foo {a :: Int} | Bar {b :: String}
derive instance genericFoo :: Generic Foo

instance showFoo :: Show Foo where
   show = gShow

在PureScript中使用无类型数据是使用purescript-foreignpurescript-argonaut库完成的。 我建议argonaut。

具有未知字段和未知类型的记录的表示将是: purescript-maps包中的StrMap Json 我建议你看看这里的(尚未合并的)文档: https//github.com/hdgarrood/purescript-argonaut-core/blob/565c7e650c51c45570663cf1838ec9cfa307a9c7/README.md 我还汇总了一个小例子,展示了如何匹配JavaScript中的异构数组:

-- src/Main.purs
module Main where

import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE, log)
import Data.Argonaut (foldJson, Json)
import Data.Foldable (traverse_)

newtype Presentation = Presentation String

unPresentation :: Presentation -> String
unPresentation (Presentation p) = p

instance showPresentation :: Show Presentation where
  show = unPresentation

class Present a where
  present :: a -> Presentation

instance presentInt :: Present Int where
  present = Presentation <<< show

instance presentNumber :: Present Number where
  present = Presentation <<< show

instance presentBoolean :: Present Boolean where
  present = Presentation <<< show

instance presentString :: Present String where
  present = Presentation

presentJson :: Json -> Presentation
presentJson =
  foldJson
    (const (Presentation "null"))
    present
    present
    present
    (const (Presentation "array"))
    (const (Presentation "record"))

foreign import vals :: Array Json

main :: forall e. Eff ( console :: CONSOLE | e) Unit
main = traverse_ (log <<< show <<< presentJson) vals

和相应的js文件:

// src/Main.js
// module Main

exports.vals = [1, 1.2, "hello", true, [1,2,3], {a: 3, b: "hi"}];

运行此程序可以为您提供:

> pulp run
* Building project in/home/creek/Documents/so-christopher-done
* Build successful.
1.0
1.2
hello
true
array
record

是的,来自purescript-debug traceAny和相关函数。 以下是一些示例: test / Main.purs#L22 我发布了Pursuit的链接,但目前似乎没有purescript-debug

暂无
暂无

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

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