如何将值转换为字符串?

How to convert a value to a string?

我正在尝试向控制台打印一个不是字符串的值。

在本例中,它是一个整数数组。

如何将允许此类行为的数组或任何其他值转换为字符串。

module Main where

import Prelude
import Control.Monad.Eff.Console
import Data.Array


main = log [1, 2, 3, 4, 5]

当我 运行 以上编译器给出以下错误:

Could not match type

  Array Int

  with type

  String


while checking that type Array t0 is at least as general

as type String while checking that expression

  [ 1, 2, 3, 4, 5 ]

has type String in value declaration main

where t0 is an unknown type

将数组转换为字符串的确切方式取决于您需要对该字符串执行的操作。也就是说,这取决于谁将使用该字符串以及如何使用。可能性范围从将它变成字符串 "array" 一直到二进制 base64 编码。

如果您只需要将其打印出来用于调试或教育目的,请使用 function show from type class Show。有一个为数组定义的类型 class 的实例,因此该函数将适用于您的情况。

main = log $ show [1,2,3,4,5]

如果您想走捷径,请使用函数 logShow,它确实执行上述操作:

main = logShow [1,2,3,4,5]

另一种为调试打印内容的方法是 the traceAny function from Debug.Trace。此函数不需要 Show 实例,因为它使用本机 JavaScript console.log,它只会转储您的值的原始 JSON 表示:

main = traceAny [1,2,3,4,5] \_ -> pure unit

注意:此函数仅用于调试,请勿将其用于可靠输出。