gpt4 book ai didi

Haskell 函数到 Clojure 函数的转换

转载 作者:行者123 更新时间:2023-12-05 08:52:34 25 4
gpt4 key购买 nike

尝试将 Haskell 函数转换为 Clojure。但面临困难。不确定发生了什么。

这是递归的 Haskell 函数。

  mapWidth :: [[Char]] -> Int
mapWidth [] = 0
mapWidth (x:xs)
| length xs == 0 = length x
| length x /= length (xs!!0) = -1
| otherwise = mapWidth(xs)

这是我到目前为止尝试过的:

(defn mapWidth [data_list]
(def data 0)
([[x & xs](seq data_list)](if (= (count x) 0)
(data 0)
(data -1))))
([[x & xs](seq data_list)](if not(= (count xs) length (xs!!0))
(data 0)
(data -1)
mapWidth(xs)))

感谢任何帮助。我对这两种语言都很陌生。

最佳答案

据我所知,如果所有元素的长度都相等,则此函数返回元素的长度。在这种情况下,它可能看起来像这样:

(defn map-len [[x & [y :as xs]]]
(cond (empty? xs) (count x)
(not= (count x) (count y)) -1
:else (recur xs)))

这几乎是对 haskell 变体的完全重写(用 recur 代替直接递归调用)

(map-len [[1 2] [3 4] [5 6]])
;;=> 2

(map-len [[1 2] [3 4 5] [5 6]])
;;=> -1

bot 因为 clojure 是关于序列操作的,你可以用更惯用的方式来做(对我来说,它是):

(defn map-len2 [data]
(cond (empty? data) 0
(apply = (map count data)) (count (first data))
:else -1))

(defn map-len3 [[x & xs]]
(let [c (count x)]
(if (every? #(= c (count %)) xs)
c
-1)))

关于Haskell 函数到 Clojure 函数的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56354251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com