Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply functions to each tuple in a list

Tags:

f#

Excuse me if this is quite basic, I'm new to functional programming and F#.

I have to create a function that takes a list of tuples (string*int) and return a list of tuples (string *int)

So basically I want to apply some functions to each tuple in pairList and return a list of tuples.

I am guessing I could do this through a recursive function.

I have the following code so far:

let rec aFunction (pairList:List<string*int>): List<string*int> =
  match pairList with
  | [] -> []
  | head :: tail ->  [fst head,snd (someFunc1 (someFunc2 (fst head,snd head)))]

This basically just apply the various functions to only the head of the list and return me a list of tuple.

In order to get it working for the whole list I tried the following:

| head :: tail ->  [fst head,snd (someFunc1 (someFunc2 (fst head,snd head)));aFunction tail]

But I get the following error :

This expression was expected to have type string * int but here has type List < string * int >

like image 411
Ying Yangz Avatar asked Sep 22 '16 01:09

Ying Yangz


2 Answers

This function does in fact exist already - it is called List.map.

To analyse your error, when you do [a;b] a and b need to have the same type.

What you wanted was to use the concatenation operator :: like this:

| head :: tail ->  (fst head,snd (someFunc1 (someFunc2 (fst head,snd head)))) :: (aFunction tail)

but you can actually make this neater by pattern matching in a better way

| (a,b) :: tail ->  (a,snd (someFunc1 (someFunc2 (a,b)))) :: (aFunction tail)
like image 132
John Palmer Avatar answered Oct 11 '22 18:10

John Palmer


John Palmers answer is more than good enough, but I would probably also go all the way and do about the following for clarity and readability:

let someFunc1 = id //just to make it compile
let someFunc2 = id //just to make it compile

let someFunc3 = someFunc2 >> someFunc1 >> snd
let someFunc4 head = fst head, someFunc3 head 

let rec aFunction (pairList:List<string*int>): List<string*int> =
  match pairList with
  | [] -> []
  | head :: tail -> someFunc4 head :: (aFunction tail)
like image 35
Helge Rene Urholm Avatar answered Oct 11 '22 17:10

Helge Rene Urholm