开发者

Simplifying an ugly function in Haskell

开发者 https://www.devze.com 2023-01-29 02:36 出处:网络
I have defined the function f1 f1 p = foldl (\\x y -> x ++ y ++ \"\\t\") \"\" (map (foldl (++) \"\") p)

I have defined the function f1

f1 p = foldl (\x y -> x ++ y ++ "\t") "" (map (foldl (++) "") p)

that will take

[["4","0","1"],["5","2","3"]]

and yi开发者_Go百科eld

"401\t523\t"

but is a function as ugly as it can get. I am sure there is a simpler way to implement the same function. Can anybody give me some clue about it?


Function composition is your friend. So is intercalate, from Data.List

f1 = intercalate "\t" . map concat

Edit: whoops, misread your output. You want "\t" at the end of all of them, not just between them. In that case, it's closer to

f1 = concat . map ((++ "\t") . concat)


As a suggestion for the approach to solving something similar to this in the future (supplimenting Carl's actual solution), what you could do is look at how a Haskell library solves the problem. For example, Data.List.unwords does something similar to what you want.

So, you might try looking into:

http://hackage.haskell.org/packages/archive/base/4.3.0.0/doc/html/Data-List.html

Finding unwords in this document, you'll notice there is a "source" link. Clicking there will bring you to the source of how the library implements it. Usually, the function isn't that large and may give you some ideas on how to generalize (or specialize) your function from the library.

0

精彩评论

暂无评论...
验证码 换一张
取 消