Haskell显示字符串分为8列 [英] Haskell Display String into 8 columns
问题描述
我有类型人员=(字符串,浮点数,浮点数,[Int])**名称,身高,体重,过去一周的英里数**
I have type person = (String, Float, Float, [Int]) ** name, height, weight, miles walked past week**
[Int]将包含该人在过去7天内每天走了多少英里的数据例如[5,8,12,7,12,6,9]
The [Int] will contain data for how many miles the person walked on each day for the past 7 days e.g. [5,8,12,7,12,6,9]
我的testData由多个人数据组成,我想以一个字符串的形式返回他们走过的里程的所有名称和7个每日数字,整齐地分成每个人的单独行,并将走过的里程数据按列排列.
My testData consists of multiple peoples data and I want to return all names and the 7 daily figures of the miles they walked as a single string, neatly into separate rows for each person and have the miles walked data lined up in columns.
例如testData = [(John,1.76,63,[5,8,12,7,12,6,9]),(Hannah,1.64,56,[6,9,10,9,5,13,13]),(刘易斯,1.80、73,[4,6,2,6,8,4,6])]
e.g. testData = [(John, 1.76, 63, [5,8,12,7,12,6,9]), (Hannah, 1.64, 56, [6,9,10,9,5,13,13]), (Lewis, 1.80, 73, [4,6,2,6,8,4,6])]
我希望这样返回:
在haskell中执行此操作的最佳方法是什么?谢谢
what is the best way to do this in haskell? Thanks
我的代码-
personToString :: [Person] -> String
personToString [] = []
personToString ((name,height,weight,miles):person)=
name ++ take (9 - length name) (cycle " ") ++ intercalate ", " (map show miles) ++ "\n \n" ++ personToString person
这将返回我想要的内容,但英里数未对齐,因为有一位数字和两位数字的组合
This returns what I want but the miles digits don't line up as there is a mix of single and double digit figures
推荐答案
OK, somebody took the trouble of putting together module Text.Printf.
这里似乎只是裁员了,所以让我们尝试一下:
Seems just a job cut for it here, so let's give it a try:
import Data.List (intercalate)
import Text.Printf
type Person = (String, Float, Float, [Int]) -- ** name, height, weight, miles...
testData :: [Person]
testData = [("John", 1.76, 63, [5,8,12,7,12,6,9]),
("Hannah", 1.64, 56, [6,9,10,9,5,13,13]),
("Lewis", 1.80, 73, [4,6,2,6,8,4,6])]
showMileList :: [Int] -> String
showMileList mileList = intercalate "," $
map (printf "%3d") mileList
personToString :: Person -> String
personToString (name, h, w, miles) =
(printf "%-9s" name) ++ " " ++
(printf "%5.2f " h) ++ (printf "%3.0f " w) ++
(showMileList miles)
printAsLines :: [String] -> IO ()
printAsLines xs = mapM_ putStrLn xs -- a loop in the IO monad
main = do
let strings = map personToString testData
printAsLines strings
程序输出:
John 1.76 63 5, 8, 12, 7, 12, 6, 9
Hannah 1.64 56 6, 9, 10, 9, 5, 13, 13
Lewis 1.80 73 4, 6, 2, 6, 8, 4, 6
我发现这很容易,在ghci下很难使用该模块: printf
上键入内容的任何松动似乎都会破坏交互式编译器.
Sole hitch in the deal I could find, the module is a bit hard to use under ghci: any looseness in the typing around printf
seems to derail the interactive compiler.
这篇关于Haskell显示字符串分为8列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!