所以我在Haskell中编写一个程序,它接收一个数字n告诉它返回从2开始的第n个素数作为第一个素数.程序的那部分工作然而我不理解的是如何让程序在数字为0或更少时抛出异常.
pr :: Int -> Int
pr n = (filter(\x -> (getter) == []) [2..]) !! (n-1)
Run Code Online (Sandbox Code Playgroud)
getter引用了我编写的另一个解决主要问题的方法.它工作正常.
默认情况下,如果函数的方程式与给定的参数不匹配,则会出现运行时错误:
fromJust :: Maybe a -> a
fromJust (Just a) = a
-- No case for Nothing
-- fromJust Nothing throws error at runtime
Run Code Online (Sandbox Code Playgroud)
但是,这对数字不起作用.相反,警卫会做类似的事情:
assertOver0 :: Int -> ()
assertOver0 n | n > 0 = ()
-- No case for n <= 0
-- assertOver0 (-1) throws error at runtime
Run Code Online (Sandbox Code Playgroud)
虽然这是默认行为,但是不完整的模式/警卫是不好的风格.相反,使用error或显式导致错误undefined:
pr n | n >= 0 = filter (null . getter) [2..] !! n
| otherwise = error "Table flip"
-- undefined is just like error, except that error lets you give an error message
-- and undefined doesn't (undefined is more useful when you know it will never
-- be evaluated, and you don't need to give an error message)
-- undefined :: a; error :: String -> a
-- That is, they can take on any type you want them to have, because whatever code
-- is after them will never be executed anyway
-- I took liberties with your definition of pr. Your filtering function didn't use
-- x, so I wrote what I think you meant. I also made it 0-indexed.
-- Prelude.null checks for [], but doesn't incur an Eq constraint, so I replaced
-- (== []) with it.
-- Parens are not needed around the filter, because function application has
-- the highest precedence.
Run Code Online (Sandbox Code Playgroud)
Haskell也有一个更复杂的异常机制Control.Exception,但你可能不需要这里.一般来说,异常和部分函数被忽略,(因为你只能处理它们IO),你应该努力寻找monad Maybe或者monad Either.
import Control.Monad
pr n = do guard $ n >= 0 -- guard True = Just (); guard False = Nothing (in this case)
return $ filter (null . getter) [2..] !! n
pr 2 = Just 5
pr (-1) = Nothing
Run Code Online (Sandbox Code Playgroud)
但这一切都是不必要的.(!!)已经出现负面指数的错误
ghci> "abc" !! -1
*** Exception: Prelude.!!: negative index
Run Code Online (Sandbox Code Playgroud)
所以我们回到了我们开始的地方:
pr n = filter (null . getter) [2..] !! n
Run Code Online (Sandbox Code Playgroud)
还有一个库重新定义列表操作(包括(!!))是monadic而不是partial.
| 归档时间: |
|
| 查看次数: |
432 次 |
| 最近记录: |