Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a string starts with one of several options in Clojure

Tags:

clojure

I want to find out if a string starts with one of several different options. For example, I want to know if a string starts with any vowel ("a" or "e" or "i" or "u").

I believe I should be using Clojure's starts-with?, but I don't know where to go from there. I have tried using a regular expression but couldn't get that right. I also tried using (or "a" "e" "i" "o" "u") but that also wasn't right.


EDIT: after more experimentation it seems that
(re-matches #"^[aeiou].*" string)
works, but I don't know if that's the best way to do it

like image 860
marbiru Avatar asked Nov 17 '18 10:11

marbiru


2 Answers

Regex is fine. Without regex:

(contains? (set "aeiou") (first "apple"))
like image 177
Michiel Borkent Avatar answered Sep 27 '22 19:09

Michiel Borkent


To use starts-with?, you'd need to iterate the list of vowels. I'd use some for helping with this since you just care if some vowel is contained at the start of the string:

(some #(s/starts-with? "hello" (str %)) "aeiou")
=> nil

(some #(s/starts-with? "apple" (str %)) "aeiou")
=> true

Honestly though, I'd just do what @Michiel has already suggested and do a set lookup, although I'd do it a little differently:

(-> "apple"
    (first) ; Is the first letter
    #{\a \e \i \o \u}) ; In the set of vowels?
=> \a ; Truthy!

(-> "hello"
    (first)
    #{\a \e \i \o \u})
=> nil
like image 43
Carcigenicate Avatar answered Sep 27 '22 19:09

Carcigenicate