Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: List mapping a function with 2 inputs

Tags:

ocaml

I have a function sqrt which takes 2 floating point values, tolerance and number and gives out square root of the number within the specified tolerance. I use approximation method to do it.

let rec sqrt_rec approx tol number =
..................;;
let sqrt tol x = sqrt_rec (x/.2.0) tol x;;

I've another function map which takes a function and a list and applies the function to all elements of the list.

let rec map f l = 
match l with
[] -> []
| h::t -> f h::map f t;;

Now I'm trying to create another function all_sqrt which basically takes 1 floating point value, 1 floating point list and maps function sqrt to all the elements.

let all_sqrt tol_value ip_list = List.map sqrt tol_value ip_list;;

It is obviously giving me error. I tried making tol_value also a list but it still throws up error. Error: This function is applied to too many arguments; maybe you forgot a `;'

I believe i'm doing mapping wrong.

like image 676
Sunday Programmer Avatar asked Feb 24 '23 03:02

Sunday Programmer


2 Answers

The List module contains

val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list

which is used like this:

let all_sqrt tol_value ip_list = List.map2 sqrt tol_value ip_list
like image 53
antonakos Avatar answered Feb 26 '23 12:02

antonakos


This sounds like homework, since you say you are limited to certain functions in your solution. So I'll try to give just some suggestions, not an answer.

You want to use the same tolerance for all the values in your list. Imagine if there was a way to combine the tolerance with your sqrt function to produce a new function that takes just one parameter. You have something of the type float -> float -> float, and you somehow want to supply just the first float. This would give you back a function of type float -> float. (As Wes pointed out, this works because your sqrt function is defined in Curried form.)

All I can say is that FP languages like OCaml (and Haskell) are exceptionally good at doing exactly this. In fact, it's kind of hard not to do it as long as you mind the precedences of various things. (I.e., think about the parentheses.)

like image 42
Jeffrey Scofield Avatar answered Feb 26 '23 11:02

Jeffrey Scofield