How do I convert a value of type List to a String in Elm?
Basically I'm looking for a function with the signature a -> String or List -> String.
Example
Let's say I have a function intAverage:
intAverage l = case l of [] -> 0 otherwise -> Debug.log (<<SHOW_FUNCTION>> l) (List.sum l // List.length l) Here I want to inspect the list, in order to understand what's being passed to my function. Debug.log expects a String which makes me look for a function with the signature a -> String or List -> String but I have been unsuccessful in finding such a function in the Elm package docs.
Haskell has Debug.traceShow (which is simply an application of the function show on the first argument of Debug.trace) but I can't find the equivalent in Elm.
3 Answers
Edit: This is no longer true as of Elm version 0.19. See the other answer to this question.
The toString was what I was looking for, but couldn't find.
toString :: a -> String I found it in the Basics-package: toString documentation
On Elm 0.19, it's been moved to Debug.toString:
For example:
> Debug.toString [1,2,3] "[1,2,3]" : String 1And if you want to convert a List to a String in Elm, in production, without the Debug library you can do:
yourList |> List.map String.fromInt |> String.join ", " for a list of Int, it will print the integer values comma separated: 1, 2, 3, 4.
Or, if you want it to be more general, not just for Int, you can create a reusable utils function:
listToString : (a -> String) -> String -> List a -> String listToString convert separator list = "[" ++ (list |> List.map convert |> String.join separator) ++ "]" with the square brackets at the ends if you like, and convert function and separator as parameters.
Usage with a list of Int would be:
yourList |> listToString String.fromInt ", " to print [1, 2, 3, 4], but you can apply it to a list of any type.
You can use it recursively too, to print a list of lists. For example [ [1, 2, 3], [10, 20, 30] ]. I will leave this as an exercise for the reader to figure out the function calls in this case.
Thanks to @glennsl for the useful suggestion down in the comments.
2