简体   繁体   中英

Why does filter not return the result of predicate function?

I am starting to learn Clojure, but I don't understand why the below code doesn't works as expected.

Given a string, I want it to print all words longer than 2 characters with the first letter capitalized.

Expected output: ("Fine" "Day")
Actual output: ("fine" "day")

(ns exploring
    (:require [clojure.contrib.string :as str]))

(defn a-function [word]
    "Capitaliza todas palavras maiores que 2 chars"
    (if (>(count word ) 2) (str/capitalize word)))

(use '[clojure.contrib.str-utils :only (re-split)])
(filter a-function (re-split #"\W+" "A fine day it is"))

I would use map in addition to filter:

(ns exploring
  (:require [clojure.string :as str])
  (:use '[clojure.contrib.str-utils :only (re-split)])

(def a-function
  [word]
  (> (count word) 2))

(map str/capitalize
     (filter a-function
             (re-split #"\W+" "A fine day it is")))

您可以将keep与原始a-function

(keep a-function (re-split #"\W+" "A fine day it is"))

If the order in which the capitalized words are returned is not important you can also do:

(reduce #(if (> (count %2) 2) (cons (str/capitalize %2) %) %) nil (re-split #"\W+" "A fine day it is"))

Resulting in ("Day" "Fine")

I'm not claiming this is better, just another way to solve the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM