当前位置: 动力学知识库 > 问答 > 编程问答 >

list comprehension - Tower of Hanoi-Haskell

问题描述:

I am really new using Haskell. I was trying to write an h4 function, which will calculate the minimum steps to finish the tower of Hanoi using 4 piles. I already got how to calculate it using 3 piles or h3. My main issue is using the list comprehension and returning the minimum value and also using Memoization to make sure I can run my code quick. I forgot to include that I am having an error when I run my h4 function. it is saying there is an issue with "|". I am new to haskell and can not debug because I am not sure what the problem is.

This is What I have below: My h3 function works fine. I need help mainly with my h4

h3 :: Int -> Integer

h3 0 = 0

h3 n = 2 * h3 (n - 1) + 1

h4 :: Int -> Integer

h4 0 = 0

h4 n = 2 * h4 (k) + h3 (n - k) | k <- [0..n-1]

h4 n = minimum [2 * h4 (k) + h3 (n - k) | k <- [0..n-1] ]

My pseudo code is:

Function H4 (n):

if n < = 0 then return 0

else

for k from 0 to n - 1

calculate the value of 2 * H4 (k) + H3 (n - k)

create a list containing these n values

return the minimum value of the list.

I appreciate all the help and advise. I decided to improve my h4 function by adding the memoized function to make sure I get my output faster. When I run my h4 memoized function I get this error :16:1: Not in scope: `memoized_h4'h3 :: Int -> Integer

--h3 function

h3 0 = 0

h3 n = 2 * h3 (n - 1) + 1

h4 :: Int -> Integer --h4 function

h4 0 = 0

h4 n = minimum [2 * h4 (k) + h3 (n - k) | k <- [0..n-1] ]

main :: IO ()

main = print $ h4 4

--memoized h4

memoized_h4 :: Int -> Integer

memoized_h4 = (map 1H4 [0..] !!)

where 1H4 0 = 0

1H4 n = memoized_h4 h3 (n - k) | k <- [0..n-1] + memoized_h4 (2 * h4 (k) )

网友答案:

As to your syntax error, here's your code again, realigned:

h4 :: Int -> Integer
h4 0 = 0
h4 n =          2 * h4 (k) + h3 (n - k) | k <- [0..n-1]          
h4 n = minimum [2 * h4 (k) + h3 (n - k) | k <- [0..n-1] ]

It is easier to see what's missing, now. | here is a part of list comprehension, i.e. it is to appear inside [ .... ]. It can't appear on its own here.

Your 3rd line above is in error, but perhaps it isn't needed at all.

(you really should include the error message in full, when posting on SO. Please always do so in the future.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: