简体   繁体   中英

Load a function but ghci doesnt seem to have compiled it

I have ran into this problems few times before but not sure what the cause is. I just simply close the command window and reopen. For ex, I enter u in the compiler and nothing happens (dont know how to explain this, better if you try it yourself). Would be great if sb can explain me the problem and how to fix it!

u = let a = 2
        b = a + (let a = 3
                 in a+b)
    in b*b

Your function is pretty nonsensical, do you know that? Lets do a little math, shall we.

module Q54272249 where

u :: Integer -- this tells you that `u` takes nothing and returns an Integer
u = let a = 2
        b = a + (let a = 3
                 in a+b)
    in b*b

Just substituting the inner a with the constant 3

u' :: Integer
u' = let a = 2
         b = a + (3+b)
     in b*b

Doing the same for the outer a

u'' :: Integer
u'' = let b = 2 + (3+b) in b*b

Addition is associative

u''' :: Integer
u''' = let b = 5+b in b*b

Replacing the let binding with an equivalent function

u'''' :: Integer
u'''' = (5 + u'''') ^ 2

Do you see the problem now? It is a function that takes no arguments and returns a value of type Integer that is 5 added to itself squared. What is the value of itself at some point in time? You recursively evaluate it and never get an answer.

We can fix that though. Make the function take an argument and establish a termination criterion like so.

u''''' :: Integer -> Integer
u''''' 0 = 0
u''''' x = (5 + u''''' (x - 1)) ^ 2

x gets smaller by 1 with every call and when it hits 0 it will return 0 or any other value you would like to. That is called recursion and it's always the same, establish one or more basecases and a recurrence relation.

Note that recurrence relations are the counterpart in discrete mathematics to differential equations in analysis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM