Please help me out with syntax mistakes

fun rappend(L1,L2)
    if null L2 then L1
    else rappend(tl(L2) @ L1, hd(L2))

Dani AI

Generated

already hit the main issues: SML function headers need the fun ... = form, and using hd/tl/null plus repeated list-concatenation (@) is both unsafe (exceptions on empty lists) and can be inefficient. The idiomatic, tail-recursive way to implement "reverse-append" (append the reverse of one list onto another) uses pattern matching and the cons operator.

fun rappend ([], ys) = ys
| rappend (x::xs, ys) = rappend(xs, x::ys)

This returns the same as rev(xs) @ ys but runs in linear time in the length of the first argument and is tail-recursive. Example evaluation: rappend([1,2,3],[4,5]) yields [3,2,1,4,5]. To reverse a list xs, call rappend(xs, []).

Notes and cautions:

  • Prefer pattern matching (x::xs) over hd/tl and null. Pattern matching explicitly handles the empty case and avoids runtime exceptions.
  • Avoid using @ inside the recursive step to build up results; repeated concatenation inside recursion can make the algorithm O(n^2).
  • The type is 'a list * 'a list -> 'a list, so both arguments must be lists of the same element type.

This approach is concise, safe, and efficient for the reverse-append task.

figured it out. Stupid syntax :(.

Here's the answer

rappend(L1,L2)
    if null L2 then L1
    else rappend(tl(L2)@L1,[hd(L2)])

darn I can't seem to figure out how to do reverse append.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.