SML中的溢出:指数化过程

时间:2017-10-12 10:35:02

标签: overflow sml exponentiation

我正在尝试编写一个简单的程序,在标准ML语言中计算x到17的幂。我应该用“帮助程序”来做到这一点:

fun help (y:int) = y * y * y * y;

fun power17 (x:int) = help (help (help (help (x) ) ) ) * x;

这会导致溢出。有人可以告诉我它为什么会这样做吗?

2 个答案:

答案 0 :(得分:1)

您正在获得整数溢出。如果您希望代码有效,则需要使用LargeInt.int

  fun help (y: LargeInt.int) = y * y * y * y;

  fun power17 (x: int) =
    let
      val x' = Int.toLarge x
    in
      help (help (help (help (x')))) * x'
    end;

还有一件事,那段代码不是在计算x ** 17,而是在做x ** 257

您应该只拨打help两次:

  fun power17 (x:int) = (help (help x)) * x;

答案 1 :(得分:0)

您的功能无法计算17的功效。评估它:

fun power17 x = help x * help x * help x * help x * x

也许你打算写:

fun power (x, 0) = 1
  | power (x, n) = x * power (x, n-1)

fun power17 x = power (x, 17)

这听起来像递归的理想情况:

rows = []
tables = soup.findAll('table', {'width': '75%'}) # tables = soup.findAll('table') works just as fine
for table in tables:
    trows = table.findAll('tr', {'class': 'boldtxt'})

    # this part extracts the header info from each table
    term = trows[0].text.strip()
    instructor, dept = [td.text.strip() for td in trows[1]]
    course, section, title = [td.text.strip() for td in trows[2]]
    enrolled, ref, completed = [td.text.strip() for td in trows[3]]

    # specifying multiple values for the 'class' attribute will search for
    # 'tr' tags having 'class' attributes of both 'tableback1' and 'tableback2'
    trows = table.findAll('tr', {'class': ('tableback1', 'tableback2')})

    # this part retrieves the main data found in the rows of the table
    for trow in trows:
        # if you choose to ignore the header part of the table,
        # make sure you remove the first part from this line
        rows.append([term, instructor, dept, course, section, title, enrolled, ref, completed]
            + [td.text.strip() for td in trow.findAll('td')])