Search code examples
recursionsmlsmlnj

Making a Star Triangle in SML


I have just started coding in SMLNJ and have been having some trouble making a program that returns a string in a triangular star pattern. For example triangle(5) should output:

*****
****
***
**
*

My code so far is:

fun triangle(x) =  
    if (x = 0) then "\n"  
    else   
        let  
            fun makeTriangle(n) =  
                if(n = 0) then "\n" else "*"^makeTriangle(n-1);  
        in  
            makeTriangle(x);  
        end  
        triangle(x-1)  

I am getting the error "triangle.sml:9.3 Error: syntax error: inserting EQUALOP". Any help would be appreciated.


Solution

  • There are at least two issues with your code:

    First, there is a simple operator precedence issue:

    if(n = 0) then "\n" else "*"^makeTriangle(n-1)
    

    parses as

    (if(n = 0) then "\n" else "*") ^ makeTriangle(n-1)
    

    rather than your intended

    if(n = 0) then "\n" else ("*" ^ makeTriangle(n-1))
    

    The solution is to put in the needed parentheses.

    Another issue is the stray line triangle(x-1) at the bottom of the function. It is unrelated to the code above it. If your intention is to concatenate it to the result of the function call makeTriangle(x) then you would need to do the explicit concatenation. There really shouldn't be anything in your function definition after the end since that end terminates the else part.

    A minor issue: since your function makeTriangle inserts "\n", your code (after fixed) will have two "\n" at the bottom of the triangle. If that isn't what you want, perhaps you can think about the basis case (n=0).