6

I'm looking for an idiomatic way to write a function List Char -> String in Purescript.

This seems like a simple thing to do, but I'm new to Purescript and have been browsing documentation for a while now with no progress!

Background information: I am porting a simple function from Haskell to Purescript

generateId :: Int -> [Char]

This generates a String of specified length. It was quite easy to convert the code to use List Char operations (where List is from Data.List in Purescript). In Haskell [Char] is the same as String so no other processing is needed, however, I can't find a function to convert from List Char to a native String in Purescript!

My search lead me to fromCharArray :: Array Char -> String in Data.String, however I could not find a way to convert from List Char to an Array Char!

I could manually convert between them by folding over List Char and building an Array Char using snoc, but surely I must be missing an inbuilt solution for what seems like basic String manipulation in Purescript!

Edit: fromList works to convert from any Unfoldable (such as Arrays) to a List. Still leaving this question open in case there is a more idiomatic way of achieving this.

sclv
  • 38,665
  • 7
  • 99
  • 204
Anupam Jain
  • 7,851
  • 2
  • 39
  • 74

2 Answers2

6

I agree with your edit. Data.String.fromCharArray <<< Data.List.fromList sounds pretty decent to me. fromCharArray is implemented in native JS with array.join("").

Update: fromList is deprecated now - use toUnfoldable instead

stholzm
  • 3,395
  • 19
  • 31
2

[Updated Jan 2021]

In PureScript 0.13.8:

import Prelude 

> import Data.Array (toUnfoldable)
> import Data.String.CodeUnits (fromCharArray)
> fromListChars = fromCharArray <<< toUnfoldable
> fromListChars ['2', '0', '2', '1']
"2021"

> fromListChars []
""