[Haskell] CodeWars|Who likes it?

https://www.codewars.com/kata/5266876b8f4bf2da9b000362/haskell

题目

你可能知道Facebook的点赞系统(404网站)和其他页面。人们可以给一个博文、图片或其他内容点赞。我们希望构造一个文本并展示给用户谁给这篇博文点赞。

实现函数likes :: [String] -> String,输入由人名构成的字符串数组。返回值例子如下:

likes [] = "no one likes this"
likes ["Peter"] = "Peter likes this"
likes ["Jacob", "Alex"] = "Jacob and Alex like this"
likes ["Max", "John", "Mark"] = "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] = "Alex, Jacob and 2 others like this"

对于多于4个人名的情况,只需要改2 others里的数字即可(前面2个人名也要改。。)。

题解

没啥好讲的,pattern matching挺好用的。

module Likes where

likes :: [String] -> String
likes [] = "no one likes this"
likes [x] = x ++ " likes this"
likes [x, y] = x ++ " and " ++ y ++ " like this"
likes [x, y, z] = x ++ ", " ++ y ++ " and " ++ z ++ " like this"
likes (x:y:xs) = x ++ ", " ++ y ++ " and " ++ show (length xs) ++ " others like this"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值