简体   繁体   中英

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

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. 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 . 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?

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

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