Concatenate strings in ocaml with newline between them
Asked Answered
P

2

8

I'd like to do something like this

String.concat '\n' [str1; str2 ... strn]

so I can print in a file. But ocaml doesn't allow me to do that. What can I do?

Peterec answered 3/4, 2012 at 2:22 Comment(0)
T
15
String.concat "\n" [str1; str2 ... strn]

works fine. The problem is that you used '\n', which is a character literal, not a string. Example:

# String.concat '\n' ["abc"; "123"];;
Error: This expression has type char but an expression was expected of type
     string
# String.concat "\n" ["abc"; "123"];;
- : string = "abc\n123"
Tarrel answered 3/4, 2012 at 2:28 Comment(1)
How would you have String.concat print "abc" and "123" on two different lines`?Radu
G
1

If you're using Jane Street's base module for your standard library you'll have to do it like so:

# #require "base";;
# open! Base;;
# String.concat ~sep:"\n" ["abc"; "123"];;
- : string = "abc\n123"

Jane Street really likes to take advantage of named arguments.

Golconda answered 14/10, 2022 at 1:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.