简体   繁体   中英

OCaml: Pad List with Zeros using Folding

I've been stuck on this for hours now - wondering if anyone could help me out.

I have two Lists of different lengths, and I want to pad the shorter list with 0's so that the two lists have the same length.

I want to do this using the Folding functions, and NOT using recursion.

Any hints are very appreciated!

This sounds like a homework problem (partly due to the somewhat arbitrary restriction on the allowed solutions). So then it doesn't really help to just write the code for you--it eliminates the whole point of doing homework. However you don't give enough info to help any other way. It would be much easier to help if you showed the best code you've written during the hours you've spent on the problem, and explained why you think it doesn't work. Then people can tell you what might be wrong with the code, and give specific hints.

It's not completely clear what you mean by "the folding functions." You can't use List.fold_left2 or List.fold_right2 to fold over both lists at once, as these assume that the input lists are already the same length. This leaves List.fold_left and List.fold_right (it seems to me).

If you're allowed to make an initial pass to get the lengths of the two lists, you can fold over the shorter list to make a copy with padding added at the end. (Right fold is easiest, though it doesn't work so well for very long lists.)

One problem with this approach is that you'd have to make the padding separately, and this might require recursion (due mostly to limits of OCaml library IMHO). Another approach would be to fold over the longer list while traversing and copying the shorter one. The longer list would function as a measure telling you how much padding to add once the shorter list is exhausted. This would be quite a bit more complex.

If either approach seems worth looking at, you might start by writing a function that uses List.fold_right just to copy a list. This is pretty close to what you want to do (it seems to me).

Finding the length of a list itself is recursive. In any case, here's my crack at the problem. I used tabulate function from SML's List structure. Also, I'm assuming you're familiar with anonymous functions.

fun put_zeroes lst1 lst2 =
    let 
        val zero_nums = List.length(lst2)-List.length(lst1)
        val pad_zeroes = List.tabulate(zero_nums,fn x => 0)
        val new_lst1 = lst1@pad_zeroes                   
    in
        new_lst1
    end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM