Haskell惰性求值和重写

Haskell惰性求值和重写,haskell,Haskell,函数定义: first_threes :: [Int] -- first three numbers repeated first_threes = 1:2:3:first_threes -- th.1 take :: Int -> [a] -> [a] -- take take 0 _ = [] -- t.1 take n (x:xs)

函数定义:

first_threes :: [Int]                     -- first three numbers repeated
first_threes = 1:2:3:first_threes         -- th.1

take :: Int -> [a] -> [a]                 -- take
take 0 _ = []                             -- t.1
take n (x:xs) = x : (take (n - 1) xs)     -- t.2

sum :: [Int] -> Int                       -- summation of an Int list
sum [] = 0                                -- s.1
sum (x:xs) = x + (sum xs)                 -- s.2
我需要使用上面函数的定义重写下面的语句。我需要得到答案。我需要使用“惰性评估”来证明每个解决方案的合理性

Hugs_Main> my sum (my take 5 first_threes)
9
我试图找出20个答案,其中9个是答案。下面是我的前10个解决方案,但我想不出其他任何解决方案。有人能帮忙吗

我的前10个解决方案:

my_sum (my_take 5 first_threes)
my_sum (my_take 5 (1:2:3:first_threes))
my_sum (my_take 5 (1:2:first_threes))
my_sum (my_take 5 (2:first_threes))
my_sum (my_take 4 (3:first_threes))
my_sum (1:2:3:(my_take 2 (first_threes)))
my_sum (1:2:(my_take 3 (first_threes)))
my_sum (1:(2:my_take 3 (3:first_threes)))
my_sum (1:(my_take 4 (2:3:first_threes)))
my_sum (1:(my_take 4 (2:first_threes)))

我想这是你们老师想看到的

my_sum (my_take 5 first_threes)
-- th.1
my_sum (my_take 5 (1:2:3:first_threes))
-- t.2
my_sum (1 : my_take 4 (2:3:first_threes))
-- s.2
1 + my_sum (my_take 4 (2:3:first_threes))
-- continue yourself

关于命名法的一句话:检查你是否必须解决问题。我给了你一些重写。在每一步中,你都要用一个等式来重写你的术语。注释显示了我在重写时使用的

将来请格式化您的代码,以便其他人更容易阅读。另外,您是否只是要求我们解释您的代码?为什么你不能把你的十个评估中的每一个都复制并粘贴到一个像GHCi这样的解释器中,然后自己去看答案呢?实际上,有无数种方法来表示甚至是
first\u threes
还有类似
4+5
的东西,它也与
my\u sum(my\u take 5 first\u threes)相同
及其有效替代品。你得再努力一点precise@NiklasB. 我已经更新了这个问题,它应该更加精确和易懂。最初的几个步骤可能是这样的:
sum(5:3)
->
sum(5:2:3:3))
->
sum(1:take 4(2:3:3))
->
1+sum(4:2:3:3))
->
1+sum(2:take 3:3))
。请注意,我如何减少了可以在每一步中减少的最顶部节点。这可能就是你所说的“懒惰评估”的意思。@Kamran你在开玩笑吗?你不知道如何添加,或者。。。什么?
my_sum (my_take 5 first_threes)
-- th.1
my_sum (my_take 5 (1:2:3:first_threes))
-- t.2
my_sum (1 : my_take 4 (2:3:first_threes))
-- s.2
1 + my_sum (my_take 4 (2:3:first_threes))
-- continue yourself