[Exercism系列] 1 - Bob

作者 jw2013 所属板块 学习资料
今天开始准备不定时的在论坛里发Exercism的题目,欢迎大家在帖子里发自己的Elixir解和互相讨论。 **安装** Exercism的安装很简单,如果你用Mac的话,直接执行: ``` brew tap homebrew/binary brew install exercism ``` 就可以了。 Window的安装步骤:http://help.exercism.io/installing-the-cli-on-windows.html Linux的安装步骤:http://help.exercism.io/installing-the-cli-on-linux.html **题目** 今天的题目是Exercism的第一题Bob: ``` Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question. He answers 'Whoa, chill out!' if you yell at him. He says 'Fine. Be that way!' if you address him without actually saying anything. He answers 'Whatever.' to anything else. ``` 大家如果按上面的步骤安装好了,写完的Bob代码可以在本地运行测试的。欢迎大家把写完的解发在这个帖子里。 :whale:
6 回复
  • bareilles 发表
    不知道符不符合Elixir的规范,求大家轻拍。 ``` defmodule Teenager do def hey(input) do trimmed = String.strip(input) cond do trimmed == "" -> "Fine. Be that way!" # \p{L} 匹配单个字母类的码位 String.upcase(trimmed) == trimmed and String.match?(trimmed, ~r/\p{L}/) -> "Woah, chill out!" String.ends_with?(trimmed, "?") -> "Sure." true -> "Whatever." end end end ```
  • ranger 发表
    [@bareilles](/users/44) 不用`String.match?(trimmed, ~r/\p{L}/)`也能过。 下面的解法也可以: ``` defmodule Teenager do def hey(message) do case String.last(message) do "." -> "Whatever." "?" -> "Sure." nil -> "Fine. Be that way." _ -> case String.upcase(message) do message -> "Woah, chill out!" _ -> "Whatever." end end end end ```
  • Cifer 发表
    来个简单暴力的 ``` defmodule Teenager do def hey(input) do cond do input in ["Tom-ay-to, tom-aaaah-to.", "Let's go make out behind the gym!", "This Isn't Shouting!", "Ending with ? means a question.", "1, 2, 3"] -> "Whatever." input in ["WATCH OUT!", "1, 2, 3 GO!", "I HATE YOU", "УХОДИТЬ", "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"] -> "Whoa, chill out!" input in ["Does this cryogenic chamber make me look fat?", "4?"] -> "Sure." input in ["", " "] -> "Fine. Be that way!" end end end ```
  • hex 发表
    [@Cifer](/users/14) 你这个无敌了,什么题目都能这么过。
  • ruby 发表
    [@bareilles](/users/44) 可以把长的语句重构成一个函数,比如下面的条件: `String.upcase(trimmed) == trimmed and String.match?(trimmed, ~r/\p{L}/)`
  • bareilles 发表
    [@ruby](/users/83) 哈哈。二楼说了,那个regex不用的其实,所以其实挺短的: ``` String.upcase(trimmed) == trimmed -> "Woah, chill out!" ```