Search code examples
functional-programmingpurescript

How to convert a value to a string?


I am attempting to print a value which is not a string to the console.

In this case it is an array of integers.

How can I convert an array or any other value which allows such behaviour to a string.

module Main where

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


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

When I run the above the compiler gives the following error:

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

Solution

  • Exactly how you should convert an array to a string depends on what you need to do with that string. That is, it depends on who is going to consume that string and how. The possibilities range from just turning it into a string "array" all the way to binary-base64-encoding.

    If all you need is just print it out for debugging or educational purposes, then use the function show from type class Show. There is an instance of that type class defined for arrays, so the function will work in your case.

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

    If you want to take a shortcut, use the function logShow, which does literally the above:

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

    An alternative way to print out stuff for debugging purposes is the traceAny function from Debug.Trace. This function doesn't require a Show instance, because it uses the native JavaScript console.log, which will just dump the raw JSON representation of your value:

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

    Beware though: this function is for debugging only, do not use it for reliable output.