smlnj - SML - Build a new list with the elements of the original list - Error: operator and operand don't agree [literal] -
given list of numbers , want create new list element @ index i sum of i-1 elements before .
for illustration :
[1,4,6,9] -> [1,5,11,20] i've written next code :
fun sum nil = 0 | sum [x]=x | sum(x::rest)=(x+hd(rest))::sum(rest); but got :
- fun sum nil = 0 = | sum [x]=x = | sum(x::rest)=(x+hd(rest))::sum(rest); stdin:306.16-306.39 error: operator , operand don't agree [literal] operator domain: int * int list operand: int * int in expression: x + hd rest :: sum rest i can see recursive rule of (x+hd(rest))::sum(rest); reason problem , how can prepare ?
regards
look @ base of operations cases. want function homecoming list, base of operations cases should homecoming lists.
fun sum [] = [] | sum [x] = [x] | sum (x::xs) = ... i replaced nil [] because improve - doesn't matter.
another thing - never utilize hd , tl operators (there exceptions, now, don't). sure, in function, won't become problem because took care of case would, there's reason. if this:
fun foo [] = ... | foo (x::y::xs) = ... sml tell pattern matching not exhaustive, is, there patterns you've missed, means grab error @ compile-time , not @ run-time.
here's version of function works.
fun sum [] = [] | sum [x] = [x] | sum (x::y::xs) = x::sum (x+y::xs) i moved add-on recursive phone call because if add together first thing, first element of result first two elements of original list added together.
sml smlnj
No comments:
Post a Comment