From 3a981f8d584baa621e659f45f80654710daea2b1 Mon Sep 17 00:00:00 2001 From: Peter Saxton Date: Sat, 6 Jun 2020 13:09:43 +0100 Subject: split_once function for strings --- src/gleam/string.gleam | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/gleam/string.gleam b/src/gleam/string.gleam index 7c2f188..3c49c87 100644 --- a/src/gleam/string.gleam +++ b/src/gleam/string.gleam @@ -239,7 +239,7 @@ pub external fn ends_with(String, String) -> Bool = /// ## Examples /// /// > split("home/gleam/desktop/", on: "/") -/// ["home","gleam","desktop", ""] +/// ["home", "gleam", "desktop", ""] /// pub fn split(x: String, on substring: String) -> List(String) { x @@ -248,6 +248,29 @@ pub fn split(x: String, on substring: String) -> List(String) { |> list.map(with: iodata.to_string) } +external fn erl_split(String, String) -> List(String) = + "string" "split" + +/// Splits a string a single time on the given substring. +/// +/// Returns an error if substring not present. +/// +/// ## Examples +/// +/// > split_once("home/gleam/desktop/", on: "/") +/// Ok(tuple("home", "gleam/desktop/")) +/// +/// > split_once("home/gleam/desktop/", on: "?") +/// Error(Nil) +/// +pub fn split_once(x: String, on substring: String) -> Result(tuple(String, String), Nil) { + case erl_split(x, substring) { + [first, rest] -> Ok(tuple(first, rest)) + _ -> Error(Nil) + } +} + + /// Create a new string by joining two strings together. /// /// This function copies both strings and runs in linear time. If you find -- cgit v1.2.3