[1,-6ren">
gpt4 book ai didi

haskell - Haskell中有 "continue"吗?

转载 作者:行者123 更新时间:2023-12-02 11:19:42 25 4
gpt4 key购买 nike

我最近开始学习 Haskell,目前正在尝试编写基本的 Haskell 函数。

我编写了一个名为 intToRoman 的函数,它应该将整数转换为罗马数字。它将整数列表中的数字( 1400 ->[1,4,0​​,0])相除,并将每个数字转换为罗马数字,同时考虑列表的长度来确定何时是千或百。

但是,它不会停止并检查零。例如,数字 1400 将返回:

 MCD** Exception: Map.!: given key is not an element in the map
CallStack (from HasCallStack)

这是代码本身:

mapInttoRoman:: M.Map Int String
mapInttoRoman = M.fromList
[(1,"I"),(4,"IV"),(5,"V"),(9,"IX"),(10,"X"),(40,"XL")
,(50,"L"),(100,"C"),(400,"CD"),(900,"CM"),(500,"D"),(1000,"M")]

listOfInt :: Int -> [Int]
listOfInt 0 = [ ]
listOfInt c = listOfInt(c`div`10) ++ [c`mod`10]

duplicate :: String -> Int -> String
duplicate string n = concat $ replicate n string

intToRoman :: Int -> String
intToRoman 0 = ""
intToRoman c = createInt x (len-1)
where x = listOfInt c
len = length x
createInt y xz = findRoman (head y) xz ++ createInt(drop 1 y)(xz-1)
where findRoman b l
| l < 1 = mapInttoRoman M.! b
| b == 0 = " "
| l == 3 = duplicate (mapInttoRoman M.! (10^l)) b
| b == 1 = mapInttoRoman M.! (10^l)
| otherwise = mapInttoRoman M.! (b*10^l)

最佳答案

我认为您使用的算法不正确,并且您使其变得比需要的更复杂。

此外,列表并不完整,我添加了 90 和 900 个案例。

看看这段代码..我认为它非常简单,你会很容易得到它。

import qualified Data.Map as M

mapInttoRoman:: M.Map Int String
mapInttoRoman = M.fromList
[(1,"I"),(4,"IV"),(5,"V"),(9,"IX"),(10,"X"),(40,"XL")
,(50,"L"),(90,"XC"),(100,"C"),(400,"CD"),(500,"D"),(900,"CM"),(1000,"M")]

intToRoman :: Int -> String
intToRoman 0 = ""
intToRoman n | M.member n mapInttoRoman = mapInttoRoman M.! n
| otherwise = val ++ intToRoman (n-key)
where
keys = reverse (M.keys mapInttoRoman)
key = maxValidKey n keys
val = mapInttoRoman M.! key
maxValidKey n (k:ks)
| n >= k = k
| otherwise = maxValidKey n ks

测试:

enter image description here

关于haskell - Haskell中有 "continue"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com