Purescript:将可能类型转换为类型

Purescript: Convert Maybe Type to Type

以下简单代码将整数值转换为字符串值并记录它。

module Main where

import Effect (Effect)
import Effect.Console (log)
import Prelude ((<>), Unit, discard)
import Data.Int (toStringAs, radix)

type CustomerFeedback = {

  customerServiceScore :: Int,
  productQualityScore :: Int,
  onTimeDeliveryScore :: Int  

}

feedback :: CustomerFeedback
feedback = {
  customerServiceScore : 4,
  productQualityScore : 2,
  onTimeDeliveryScore : 6
}

stringifyCustomerFeedback :: CustomerFeedback -> String
stringifyCustomerFeedback feedback = "Service: " <> toStringAs (radix 10) feedback.customerServiceScore 

main ∷ Effect Unit
main = do
  log (stringifyCustomerFeedback(feedback))

但是,运行 此代码会产生以下错误:

  Could not match type
  
    Maybe Radix
  
  with type
         
    Radix
         

while checking that type Maybe Radix
  is at least as general as type Radix
while checking that expression radix 10
  has type Radix
in value declaration stringifyCustomerFeedback

问题如下:

  1. 如何更改上面的代码,使其按预期输出字符串而不是错误?

  2. 如果在本应使用 Radix 的地方使用 Maybe Radix 类型会导致错误,那么它有什么意义呢?你如何使用 Maybe 值?

radix 函数的想法是,你给它一个数字,然后它从中创建一个 Radix。但并非每个数字都构成有效的 Radix。例如,如果你给它 -5,它应该不起作用。 01 也不应该。由于某些技术原因,32 以上的基数也被视为无效。

这就是为什么它 returns Maybe:它会是 Nothing 以防你给它的数字不是“有效”基数。

并且该功能的用例是当您实际上并不提前知道数字时。就像你从用户那里得到它一样。或者来自某种配置文件或诸如此类的东西。在这种情况下,如果您得到 Nothing,您会将其解释为“无效的用户输入”或“损坏的配置文件”并相应地报告错误。而且您甚至无法调用 toStringAs。这是静态类型的一大卖点:应用得当,它们可以迫使您编写正确、可靠的程序,同时不忽略边缘情况。

但是,如果您已经知道自己对十进制基数感兴趣,只需使用decimal。它是库提供的一个 Maybe-free 常量,以及其他一些常用常量,例如 binaryoctal.

stringifyCustomerFeedback feedback = "Service: " <> toStringAs decimal feedback.customerServiceScore