简体   繁体   English

调用函数的haskell案例

[英]haskell case that calls a function

I have been at this for a long time, I cant figure out whats wrong Haskell just makes me feel so dumb 我已经待了很长时间了,我想不出什么错Haskell只是让我感到自己很笨

data Operation
    = Nth Integer


fib :: (Integral i, Integral j) => i -> j

fib   n | n == 0         = 1
        | n == 1         = 1
        | n == 2         = 1
        | n == 3         = 1        
        | otherwise = (fib(n-1)+fib(n-2))* fib(n-3) `div` fib(n-4)
main = do
command <- getLine
case command of
    Nth op -> show $ fib op
    Nothing -> "Invalid operation"

So when the user inputs Nth 9, the fib function needs to get called with n=9 and give the output to the user. 因此,当用户输入Nth 9时,需要使用n = 9调用fib函数并将输出提供给用户。 I feel like my case control structure is appropriate, but I cant get it to work at all!!! 我觉得我的案例控制结构合适,但我根本无法使它正常工作!!!

you are almost complete. 你快完成了。 use deriving (Read) for reading String as Operation . 使用deriving (Read)读取String作为Operation http://en.wikibooks.org/wiki/Haskell/Classes_and_types#Deriving http://en.wikibooks.org/wiki/Haskell/Classes_and_types#Deriving

If you want to handle read error, see How to catch a no parse exception from the read function in Haskell? 如果要处理读取错误,请参见如何从Haskell的读取函数中捕获无解析异常?

data Operation = Nth Integer deriving (Read)

fib :: (Integral i, Integral j) => i -> j

fib   n | n == 0         = 1
        | n == 1         = 1
        | n == 2         = 1
        | n == 3         = 1
        | otherwise = (fib(n-1)+fib(n-2))* fib(n-3) `div` fib(n-4)
main = do
  command <- getLine
  print $ case read command of
    Nth op -> fib op

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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