Haskell 程序从给定的年份中提取最后两位数字

haskellserver side programmingprogramming更新于 2025/5/8 5:07:17

本教程将帮助我们从给定的年份中提取最后两位数字。年份值作为参数传递给定义的函数,然后使用 Haskell 中的各种方法提取最后两位数字。并显示最终输出。

例如,对于输入的年份 = 2023,最后两位数字 = 23。

算法

  • 步骤 1 - 导入 Data.Char 模块以使用 digitToInt 函数。

  • 步骤 2 - 定义 extractLastTwoDigits 函数

  • 步骤 3 - 程序执行将从主函数开始。 main() 函数对程序有完全的控制权。

  • 步骤 4 - 初始化名为"year"的变量。它将包含要提取其最后两位数字的年份值。

  • 步骤 5 - 使用"putStrLn"语句显示最终结果的年份最后两位数字。

使用 extractLastTwoDigits 函数

extractLastTwoDigits 函数以 Int 作为参数,代表年份。init 函数用于从年份中删除最后一位数字,last 函数用于提取年份剩余数字的最后一位数字。

示例 1

import Data.Char (digitToInt)

extractLastTwoDigits :: Int -> String
extractLastTwoDigits year = [(last (init (show year))), last (show year)]

main :: IO ()
main = do
   let year = 2023
   let result = extractLastTwoDigits year
   putStrLn ( "Last two digits of the year are: " ++ result)

输出

Last two digits of the year are: 23

使用 Mod 函数

在此示例中,mod 函数返回除法的余数,div 函数返回除法的商。通过将年份除以 100,然后取余数,我们可以得到年份的最后两位数字。

示例 2

import Data.Char (digitToInt)

extractLastTwoDigits :: Int -> Int
extractLastTwoDigits year = year `mod` 100

main :: IO ()
main = do
   let year = 2021
   let result = extractLastTwoDigits year
   putStrLn ( "Last two digits of the year are: " ++ show result)

输出

Last two digits of the year are: 21

使用列表推导式

在此示例中,使用列表推导式提取年份的最后两位数字,方法是将其转换为字符串,然后使用 digitToInt 函数。

示例 3

import Data.Char (digitToInt)

extractLastTwoDigits :: Int -> [Int]
extractLastTwoDigits year = [digitToInt x | x <- (drop (length (show year) - 2) (show year))]

main :: IO ()
main = do
    let year = 2018
    let result = extractLastTwoDigits year
    putStrLn ( "Last two digits of the year are: " ++ show result)

输出

Last two digits of the year are: [1,8]

结论

在 Haskell 中,有多种方法可以提取输入的年份的最后两位数字。要提取年份的最后两位数字,我们可以使用用户定义的 extractLastTwoDigits 函数、mod 函数或列表推导。年份值作为参数传递给这些函数,然后提取年份的最后两位数字。


相关文章