I'm trying to write a function that will return the second smallest number in a list. I keep getting a syntax error but I can't really pinpoint what the issue is. Can I please get help on this?
Deleted code
You forget to close local let bindings using in. The correct (and indented) code should be:
let second_smallest_helper1 lst=
let second_smallest_helper2 currentMinimum currentNumber =
if currentMinimum < currentNumber then currentMinimum else currentNumber
in List.fold_left second_smallest_helper2 (List.hd lst) lst
;;
let delete (x, mylist) = List.filter (fun y -> y != x) mylist;;
let second_smallest myList =
let x = second_smallest_helper1 myList in
let newList = delete (x,myList) in
second_smallest_helper1 newList
;;
Top level let binding has the form
let <pattern> = <expression>;; (* ;; is optional, but beginners should have it *)
but local let binding has the form
let <pattern> = <expression> in <expression>
You absolutely need to use a proper OCaml indentation tool for your editor to avoid this kind of errors.
One more thing. I am not sure your use of != is ok. This is physical pointer comparison. Probably you want to use <>, the structural comparison.
The OP tried to edit and delete all of the answer due to "personal reasons". I myself skipped the edit approval and left it to the community, which apparently rejected it. Meta SO discussion about this kind of thing is found at What to do when an OP asks to delete my code from my answer? , including what the OP should do.
Related
In F#, I find when I want to use takeWhile, I usually also want to use skipWhile, that is, take the list prefix that satisfies a predicate, and also remember the rest of the list for subsequent processing. I don't think there is a standard library function that does both, but I can write one easily enough.
My question is, what should this combination be called? It's obvious enough that there should be a standard name for it; what is it? Best I've thought of so far is split, which seems consistent with splitAt.
span is another name I've seen for this function. For example, in Haskell
This part of your question stood out to me (emphasis mine):
take the list prefix that satisfies a predicate, and also remember the rest of the list for subsequent processing
I am guessing that you want to recurse with the rest of the list and then apply this splitting function again. This is what I have wanted to do a few times before. Initially, I wrote the function that I think you are describing but after giving it more thought I realised that there might be a more general way to think about it and avoid the recursion completely, which usually makes code simpler. This is the function I came up with.
module List =
let groupAdjacentBy f xs =
let mutable prevKey, i = None, 0
xs
|> List.groupBy (fun x ->
let key = f x
if prevKey <> Some key then
i <- i + 1
prevKey <- Some key
(i, key))
|> List.map (fun ((_, k), v) -> (k, v))
let even x = x % 2 = 0
List.groupAdjacentBy even [1; 3; 2; 5; 4; 6]
// [(false, [1; 3]); (true, [2]); (false, [5]); (true, [4; 6])]
I found this one easier to name and more useful. Maybe it works for your current problem. If you don't need the group keys then you can get rid of them by adding |> List.map snd.
As much as I usually avoid mutation, using it here allowed me to use List.groupBy and avoid writing more code.
.slice could capture the intent of a contiguous range:
List.slice skipPredicate takePredicate
Could someone explain what the |> operator does? This code was taken from the reference here:
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
I can see what it does, but I wouldn't know how to apply the |> operator otherwise.
For that matter, I have no idea what the Module.() syntax is doing either. An explanation on that would be nice too.
Module.(e) is equivalent to let open Module in e. It is a shorthand syntax to introduce things in scope.
The operator |> is defined in module Pervasives as let (|>) x f = f x. (In fact, it is defined as an external primitive, easier to compile. This is unimportant here.) It is the reverse application function, that makes it easier to chain successive calls. Without it, you would need to write
let m = PairsMap.(add (1,0) "world" (add (0,1) "hello" empty))
that requires more parentheses.
The |> operator looks like the | in bash.
The basic idea is that
e |> f = f e
It is a way to write your applications in the order of execution.
As an exemple you could use it (I don't particularly think you should though) to avoid lets:
12 |> fun x -> e
instead of
let x = 12 in e
For the Module.() thing, it is to use a specific function of a given module.
You probably have seen List.map before.
You could of course use open List and then only refer to the function with map. But if you also open Array afterwards, map is now referring to Array.map so you need to use List.map.
The |> operator represents reverse function application. It sounds complicated but it just means you can put the function (and maybe a few extra parameters) after the value you want to apply it to. This lets you build up something that looks like a Unix pipeline:
# let ( |> ) x f = f x;;
val ( |> ) : 'a -> ('a -> 'b) -> 'b = <fun>
# 0.0 |> sin |> exp;;
- : float = 1.
The notation Module.(expr) is used to open the module temporarily for the one expression. In other words, you can use names from the module directly in the expression, without having to prefix the module name.
I need to modify an OCaml function:
let removeDuplicates l =
let rec helper (seen,rest) =
match rest with
[] -> seen
| h::t ->
let seen' = failwith "to be written" in
let rest' = failwith "to be written" in
helper (seen',rest')
in
List.rev (helper ([],l));;
The function needs to take a list l and return the list with all duplicates removed. The failwith "to be written" parts is where I'm supposed to write my code. I understand how the helper function works but am having trouble understanding this part helper (seen',rest'). I'm not exactly sure how the function is supposed to flow with this part or how it works when you include a bunch of in's all together. We are allowed to use List.rev which reverses a list and list.mem which returns true if a certain element is in a list. Can someone please explain to me how the flow of the function is supposed to work so I can start to write a solution.
That line is confusing because it's indented incorrectly, or so I would claim. The proper indentation looks like this:
let seen' = failwith "to be written" in
let rest' = failwith "to be written" in
helper (seen',rest')
What it's saying is: calculate a new value for seen and a new value for rest, then call yourself recursively with the two new values.
I'm teaching myself OCaml and I sometimes need to create a function where I'm not really sure what the proper solution should be. Here's one that I'm a little confused about.
I need a function that will prompt the user for individual float values and return everything entered in a float list. I can create this function but I'm not sure if its the proper/best way to do it in Ocaml.
Here's my attempt.
let rec get_floats() =
match
(
try Some(read_float())
with
| float_of_string -> None
)
with
| None -> []
| Some s -> s :: get_floats();;
This code works buts I'm at a loss deciding if its a 'proper OCaml' solution. Note, to exit the function and return the float list just enter a non-integer value.
(I hope that) this is a simple peephole rewrite involving no thought whatsoever of the function in your question:
let rec get_floats() =
try
let f = read_float() in (* as suggested by Martin Jambon *)
f :: (get_floats())
with
| float_of_string -> []
The idea I tried to apply here is that you do not need to convert the success/failure of read_float into an option that you immediately match: just do what you have to do with the value read, and let the with handle the failure case.
Now that I think of it, I should point out that in both your question and my rewrite, float_of_string is a fresh variable. If you meant to match a specific exception, you failed at it: all exception constructors, like datatype constructors, are Capitalized. You might as well have written with _ -> instead of with float_of_string ->, and a recent version of OCaml with all warnings active should tell you that your function (or mine) binds a variable float_of_string without ever using it.
Thanks everyone for the help. This works.
let rec get_floats() =
try
let x = read_float() in
x :: get_floats()
with
| _ -> [];;
List.iter (fun x -> print_endline(string_of_float x)) (get_floats());;
let rec filtersList2fromList1 (List1:string list) (List2:string list) : string list =
let finalList = [] in
match List1 with
| s :: tl -> if List.mem s List2 = true
then finalList # [s] else filtersList2fromList1 tl List2
| [] -> []
so that,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"] would be ["x";"z"]
filtersList2fromList1 ["x";"y";"z"] ["x"] would be ["x"]
what I would like to add is, if the "if" statement is true, not only it would execute "finalList # [s]", but also "filtersList2fromList1 tl List2" so that it will be a recursion. Without executing "filtersList2fromList1 tl List2" when it is true,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"] would only be ["x"], which is wrong.
How should I solve this problem?
Thank you very much
To answer your specific question, you'd either use a semi-colon or a let...in construct. In your case, neither will do what you want however.
You should read through the documentation on the standard library, as the List module contains everything you need to do what you want:
let filterList2fromList1 list1 list2 =
List.filter (fun x -> List.mem x list2) list1
Note that since you mentioned recursion, I'm assuming that when you wrote dolls_of you meant filtersList2fromList1. Also I'm assuming that List1 and List2 are supposed to be list1 and list2, since the former would be an error.
It should also be pointed out that # is an O(n) operation and it is not recommended to use it to build up lists. However as Niki pointed out in the comments, your use of finalList is pointless, so you don't actually need # anyway.
To answer your question: You can execute two expressions after another by separating them with a ;. However dolls_of is a function without side effects, so executing it without doing anything with its result would make little sense.
What you actually want to do, as far as I can tell, is:
if List.mem s list2
then s :: filtersList2fromList1 tl list2
else filtersList2fromList1 tl list2