haskell 函数为Numeric,从其他函数调用时出错

wfypjpf4  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(129)

我从stackoverflow网站的其他用户那里获取了这个函数,它可以检查字符串是否是数字。

import Data.Char

isNumericString :: String -> Bool
isNumericString ""  = False
isNumericString "." = False
isNumericString xs  =
  case dropWhile isDigit xs of
    ""       -> True
    ('.':ys) -> all isDigit ys
    _        -> False

一个stackoverflow用户回答了一个函数,该函数接受任何类型的变量并计算它是否是一个数字

isNumeric :: Show a => a -> Bool
isNumeric x = isNumericString (show x)

现在,它可以独立地正常工作,但是当我在mcd函数本身中使用这个函数时,如果用户输入了错误的数据,而不是转到默认函数,Haskell会抛出错误。
Ejemplo:

gcf :: (Int,Int) -> Int 
gcf (x,y) = if isNumeric (x) && isNumeric (y) then
             if y == 0 then
                x                     -- base step
             else
                gcf (y, x `mod` y)    -- inductive step
            else
               error "Arguments must be numbers"

使用示例

gcf (10,25)

预期和获得的结果:

5

第二种情况:

gcf (4,"10")

预期结果:

Error: Arguments must be numbers

获得的结果:

<interactive>:15:8: error:
    • Couldn't match expected type ‘Int’ with actual type ‘[Char]’
    • In the expression: "10"
      In the first argument of ‘gcf’, namely ‘(4, "10")’
      In the expression: gcf (4, "10")
bxgwgixi

bxgwgixi1#

尝试以下修改:

import Data.Char

isNumericString :: String -> Bool
isNumericString ""  = False
isNumericString "." = False
isNumericString xs  =
  case dropWhile isDigit xs of
    ""       -> True
    ('.':ys) -> all isDigit ys
    _        -> False

isNumeric :: Show a => a -> Bool
isNumeric x = isNumericString (show x)

gcf :: (Show a, Integral a) => (a, a) -> a
gcf (x, y)
  | isNumeric x && isNumeric y =
      if y == 0 then
        x                     -- base step
      else
        gcf (y, x `mod` y)    -- inductive step
  | otherwise = error "Arguments must be numbers"

main :: IO ()
main = do
  putStrLn $ show (gcf (10, 25))   -- This will print 5
  putStrLn $ show (gcf (4, "10"))  -- This will throw an error

对于(4,“10”)params。...

import Data.Char

isNumericString :: String -> Bool
isNumericString ""  = False
isNumericString "." = False
isNumericString xs  =
  case dropWhile isDigit xs of
    ""       -> True
    ('.':ys) -> all isDigit ys
    _        -> False

isNumeric :: Show a => a -> Bool
isNumeric x = isNumericString (show x)

class GCDType a where
  gcd' :: a -> a -> a

instance GCDType Int where
  gcd' = gcd

instance GCDType Integer where
  gcd' = gcd

gcf :: (Show a, Show b, GCDType a, GCDType b) => (a, b) -> a
gcf (x, y)
  | isNumeric x && isNumeric y =
      if y == 0 then
        x                     -- base step
      else
        gcd' x y              -- inductive step
  | otherwise = error "Arguments must be numbers"

main :: IO ()
main = do
  putStrLn $ show (gcf (10, 25))   -- This will print 5
  putStrLn $ show (gcf (4, "10"))  -- This will print 2

相关问题