2

In F# you can pass a string to an int via the |> operator like this:

"54" |> int

I was wondering if there is a way to do that for list like this:

"[4;2;3]" |> list

When trying to do this for a list it errors that the value or constructor is not defined.

Perhaps this is not possible at all?

2
  • 1
    What do you expect the result to be for "[4;2;3]" |> list ? Commented Jan 24, 2017 at 11:31
  • a regular list [4;2;3] that i can extract the elements from and work with Commented Jan 24, 2017 at 11:32

1 Answer 1

6

int is a function that can convert a string (and other things) into an int.

There is no built-in function called list. To make a list you could use the list literal syntax: [4;2;3]

If you need to parse a string like "[4;2;3]" into an int list then you're on your own. You'd need to write code to do that. For example:

let parseIntList (str:string) =
    let trimmed = str.Trim()
    if not (trimmed.StartsWith "[" && trimmed.EndsWith "]") then failwith "Not a list"
    trimmed.[1 .. trimmed.Length - 2].Split ';'
    |> Array.map int
    |> Array.toList

This function works for your example but it may fail for other valid inputs.

Sign up to request clarification or add additional context in comments.

4 Comments

Should that not be int is a constructor that can construct an int from a string ?
According to the documentation of int, it is indeed not a constructor, but wraps the static Int32.Parse (did not manage to find the source code location yet)
so "1;2;3".Split ';' |> Array.map int |> Array.toList will give me the desired list. This helped me alot. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.