3

I'm tring to do a function on SML that invert the first list and then concatenate with the second list (someting like: list1 = [5,3,1] and list 2 = [ 6 7 8], then inv(list1,list2) = [ 1,3,5,6,7,8].) Here's the code:

fun inv (nil,nil) = []
|inv (ha::ta,hb::tb) = 
 if ha = [] then ta::(hb::tb)
 else  ha::inv(ta,hb::tb);

It returns this:

Error: types of if branches do not agree [circularity] then branch: ''Z list list list else branch: ''Z list list in expression:

if ha = nil then ta :: hb :: tb else ha :: inv (ta, :: )

Can anyone help me with this please?

Breno Santos
  • 174
  • 1
  • 3
  • 12

2 Answers2

4
fun inv ([], b) = b
 |  inv (h::t, b) = inv(t, h::b)

Note that you don't need pattern matching on the second list. This is a canonical example of a tail recursive function; it is the way to reverse a list with constant stack space. You error was using cons (::) where the first argument had type 'a list.

seanmcl
  • 9,740
  • 3
  • 39
  • 45
0

Since you're working with lists, if ha =[], then there is no other term remaining in list1.

jimmu
  • 1,025
  • 1
  • 10
  • 15
  • No. `ha` is the head of the list, which means that if `ha = []`, then it's a list of lists that starts with an empty list, which is not at all the intention. – Tayacan Sep 02 '13 at 22:17