4

I'm still fairly new to OCaml, and would like some assistance on optimizing code.

I'm trying to multiply each element of a given list by the list's last element.

Here's a snippet of my code:

(* Find the last element of a function *)
let rec lastE = function
| [] -> []
| [x] -> x
| _ :: t -> lastE t;;

(*multiply a list by the last element*)
let rec lmul list =
match list with
[] -> []
| hd::tl -> (hd *. (lastE tl)) :: lmul tl;;

When I run the code I get this error message:

Error: This expression has type float list but 
an expression was expected of type 'a list list

I'm been studying it for a while, but any assistance on this problem will be much appreciated.

  • 1
    I you look at the function signature for lastE you will see that it takes a' list list and returns a' list instead of a'. This is source of the first error you got. If you are able to use List.rev you can get the last element very easily. For lmul, have you thought about using List.map instead? – Dave Newman Apr 23 '13 at 02:33
  • Oh! I hadn't thought of using List.rev. That makes things much simpler. I'm unfamiliar with List.map, but I'll give that a shot. – Frustrated_Grunt Apr 23 '13 at 02:41

1 Answers1

2

To rephrase differently what Dave Newman is telling you, your basic problem is that lastE needs to handle an empty list differently. If lastE is supposed to return a number, it has to return a number in all cases. As it stands, lastE returns a list when it receives an empty list.

If you don't want to use List.map (again as Dave Newman suggests), you might at least consider calling lastE just once rather than once for each element of the list. This will make a big difference for long lists.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108