简体   繁体   中英

Purescript: Convert Maybe Type to Type

The following simple code converts an Integer value to a string value and logs it.

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))

However, running this code produces the following error:

  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

Questions would be as follows:

  1. How do you change the code above so it outputs a string as expected and not an error?

  2. What's the point of a Maybe Radix type if using it where you would use a Radix causes an error? How do you use a Maybe value?

The idea of the radix function is that you give it a number and it creates a Radix from it. But not every number constitutes a valid Radix . For example, if you give it -5 , it shouldn't work. And neither should 0 or 1 for example. For some technical reasons, radices above 32 are also deemed invalid.

So that's why it returns Maybe : it would be Nothing in case the number you gave it wasn't a "valid" radix.

And the use case for that function is when you don't actually know the number ahead of time. Like if you get it from the user. Or from some sort of config file or whatnot. In that case, if you get a Nothing , you would interpret that as "invalid user input" or "corrupted config file" and report an error accordingly. And you won't even get as far as calling toStringAs . This is one of the big selling points of static types: applied properly, they can force you to write a correct, reliable program, without ignoring edge cases.

However , in case you already know that you're interested in decimal radix, just use decimal . It's a Maybe -free constant provided by the library, along with some other frequently used ones, such as binary and octal .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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