1

I am trying to implement boolean disjunction. I have successfully implemented it using recursion, and for a bit of practice I am trying to do the same using List.fold_right but I am failing miserably.

let q1fold lst =
  List.fold_right (fun lst acc ->
    match lst with 
    | [] -> acc
    | h::t -> if h then true else false ) 
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Please don't just dump your code and ask us to fix it for you. Instead ask about a specific problem with your current implementation. See also [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822). – glennsl Nov 28 '22 at 15:30
  • 1
    what is the signature of List.fold_right? are you sure the first argument of your anonymous `fun` should be `lst`? – coredump Nov 28 '22 at 15:36
  • i am passing a lst for iteration and then accumulator is it wrong? – Dani_lucifer923 Nov 28 '22 at 18:27

1 Answers1

4

Consider the type signature of List.fold_right:

# List.fold_right;;
- : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b = <fun>

Three arguments are taken. You've only passed one. List.fold_right and List.fold_left consider an initial value and each element of the input list and runs a function on them to generate the initial value for the next iteration, returning that value at the end of the list.

What do you think the "update" and the initial values should be in the following to implement the functionality you want?

List.fold_right (fun x init -> ...) [true; false; false] ...

Note 1: I would use List.fold_left as it is tail-recursive, though for a small dataset it is unlikely to make a practical difference here.

Note 2: if h then true else false is equivalent to h.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    I am sorry this might sound dumb List.fold_right (fun lst acc -> match lst with | [] -> acc | h::t -> if h then true else false ) (lst) so is this the syntax u mean when you say 3 args and if not can you help me in figuring this problem. – Dani_lucifer923 Nov 28 '22 at 18:31
  • 1
    The first argument is a function which takes an element from the list, and the accumulated value. The second is the list itself. The third is the initial value. – Chris Nov 28 '22 at 19:12