gpt4 book ai didi

haskell - 如何在 Haskell 中重构这段代码

转载 作者:行者123 更新时间:2023-12-02 18:07:43 26 4
gpt4 key购买 nike

我编写了这个简单的代码,在终端上绘制字母。如何主要使用 Prelude 函数重构这段代码?当然,也可以使用其他库。

import Data.Char

letterDatabase = [
[
"AAAAA ",
"A A ",
"AAAAA ",
"A A ",
"A A "
],
[
"BBBB ",
"B B ",
"BBBB ",
"B B ",
"BBBB "
],
[
"CCCCC ",
"C ",
"C ",
"C ",
"CCCCC "
],
[
"DDD ",
"D D ",
"D D ",
"D D ",
"DDD "
],
[
"EEEEE ",
"E ",
"EEEEE ",
"E ",
"EEEEE "
],
[
"FFFFF ",
"F ",
"FFFF ",
"F ",
"F "
],
[
"GGGGG ",
"G ",
"G GGG ",
"G G ",
"GGGGG "
],
[
"H H ",
"H H ",
"HHHHH ",
"H H ",
"H H "
],
[
" I ",
" I ",
" I ",
" I ",
" I "
],
[
" JJJJ ",
" J ",
" J ",
"J J ",
"JJJJ "
],
[
"K K ",
"K K ",
"KK ",
"K K ",
"K K "
],
[
"L ",
"L ",
"L ",
"L ",
"LLLLL "
],
[
"MM MM ",
"M M M ",
"M M ",
"M M ",
"M M "
],
[
"N N ",
"NN N ",
"N N N ",
"N NN ",
"N N "
],
[
"00000 ",
"O O ",
"O O ",
"O O ",
"OOOOO "
],
[
"PPPPP ",
"P P ",
"PPPP ",
"P ",
"P "
],
[
"QQQQQ ",
"QQ Q ",
"Q QQQ ",
"Q Q ",
"QQQQ Q"
],
[
"RRRR ",
"R R ",
"RRRR ",
"R R ",
"R R "
],
[
"SSSSS ",
"S ",
"SSSSS ",
" S ",
"SSSSS "
],
[
"TTTTT ",
" T ",
" T ",
" T ",
" T "
],
[
"U U ",
"U U ",
"U U ",
"U U ",
"UUUUU "
],
[
"V V ",
"V V ",
"V V ",
" V V ",
" V "
],
[
"W W ",
"W W ",
"W W ",
"W W W ",
"WW WW "
],
[
"X X ",
" X X ",
" X ",
" X X ",
"X X "
],
[
"Y Y ",
" Y Y ",
" Y ",
" Y ",
" Y "
],
[
"ZZZZZ ",
" Z ",
" Z ",
" Z ",
"ZZZZZ "
]]

----------------------------------

draw :: String -> String
draw xs = concatMap (\(i, xs)-> concatMap (\ x -> letterDatabase !! (ord (toUpper x) - 65) !! (i - 1)) xs ++ "\n") (zip [1..5] (replicate 5 xs))

main = putStrLn $ draw "GAB"

最佳答案

拍摄:

draw = unlines . map concat . Data.List.transpose
. map ((letterDatabase !!) . subtract 65 . ord . toUpper)

编辑:好吧,我想我原来的镜头更像是高尔夫黑客而不是重构。这是使用 Array稍微不太容易出错的版本(我想我可以使用关联列表来避免使用 Prelude 之外的更多函数,但与 VectorMap 不同,它至少在标准中。):

import Data.Char
import Data.Array
import Data.List

-- Again leaving out the letterDatabase for brevity, see question.

letterArray = listArray ('A','Z') letterDatabase

draw :: String -> String
draw = unlines . map concat . transpose
. map (letterArray !)
. filter (inRange $ bounds letterArray)
. map toUpper

main = putStrLn $ draw "GAB"

关于haskell - 如何在 Haskell 中重构这段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430264/

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