Reputation: 2440
let sortStringAsKey (listOfWords : string array) =
let temp = listOfWords
|> Array.map (fun word -> word.ToCharArray() |> Array.sort)
|> Array.map String
|> Array.zip listOfWords
temp
Hello,
I've written some code like this that takes a list of words and sorts them and it creates a tuple like such (originalWord, sortedWord) however; I would like the tuple to look like this (sortedWord, originalWord).
I know we could simply finish the let statement and then do
let newTemp = Array.zip temp |> listOfWords
But I was wondering if there's a way to somehow reverse the curried arguments somehow so that the first argument in function is applied first. This will let me do it without using another let statement.
EDIT:
What I was thinking was that somehow... if I could reference 'temp' I could use itself as the first argument into the zip or something... although I know that won't work since it can only take 1 function and it'd just zip it with itself.
Upvotes: 4
Views: 130
Reputation: 80714
You could pipe the input into a lambda expression:
let temp = listOfWords
|> Array.map (fun word -> word.ToCharArray() |> Array.sort)
|> Array.map String
|> (fun sorted -> Array.zip sorted listOfWords)
Or you could generalize this and make yourself a function that reverses the arguments of another function. Such function is traditionally called flip
:
let flip f a b = f b a
let temp = listOfWords
|> Array.map (fun word -> word.ToCharArray() |> Array.sort)
|> Array.map String
|> (flip Array.zip) listOfWords
As an aside, I personally would do it like this:
let pairWithSorted word =
let sorted = word |> Seq.sort |> Seq.toArray |> String
sorted, word
let temp = listOfWords |> Array.map pairWithSorted
There's really no need for a zip
, and no need for ToCharArray
, because string
is IEnumerable<char>
.
Upvotes: 5