0
let total = [| "1X2"; "3X4"; "5X6" |]

let oddEven = total
            |> Array.map(fun x -> x.Split('X'))

I have an array of string, which is total in above example, I want to split the array by "X", as the oddEven in the above example, but I want to return 2 arrays of strings:

let odd = [| 1; 3; 5 |] and let even = [| 2; 4; 6 |]

It could be an easy task, but I can not figure it out now. Any help is greatly appreciated! Thanks,

0

3 Answers 3

4

You should check whether each string can split into two pieces, and unzip the result:

let total = [| "1X2"; "3X4"; "5X6" |]

let odds, evens = total |> Array.map (fun x ->  match x.Split('X') with
                                                | [|odd; even|] -> odd, even
                                                | _ -> failwith "Wrong input")
                        |> Array.unzip;;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for your great code! Besides, it is very good that your code did a careful condition check, otherwise, there could be some wrong input to ruin the results! Thanks and have a nice weekend!
Assuming this is numeric odd and even - above solution will not work correctly for let total = [| "2X1"; "3X4"; "6X8" |]
I assume the solution is for odd and even positions in each split string array.
2
let evens, odds = total 
                  |> (Array.map (fun x -> x.Split('X')))
                  |> Array.concat
                  |> Array.partition (fun s -> int s % 2 = 0)

EDIT: As John Palmer points out in the comments, you can use Array.collect instead of map and concat:

let evens, odds = total 
                    |> Array.collect (fun s -> s.Split('X')) 
                    |> Array.partition (fun s -> int s % 2 = 0);;

4 Comments

|> (Array.map (fun x -> x.Split('X'))) ----^^ stdin(26,5): error FS0010: Unexpected infix operator in binding. Expected incomplete structured construct at or before this point or other token.
@swapneel - I think it's an indentation problem - try indenting the lines after the first so they level with 'total' in the first.
@Lee - You can youse Array.collect rather than Array.map ... |> Array.concat
@JohnPalmer - Thanks, I wasn't aware of collect.
0
let odd = 
    oddEven |> Array.map (fun x -> x.[0])
let even =
    oddEven |> Array.map (fun x -> x.[1])

2 Comments

x.[1] is always 'X' and wouldn't really work with numbers larger than 9
You might just have misunderstood? oddEven is [|[|"1"; "2"|]; [|"3"; "4"|]; [|"5"; "6"|]|]

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.